{"text":"\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_FAULTS_HH__\n#define __ARCH_X86_FAULTS_HH__\n\n#include \"base\/misc.hh\"\n#include \"sim\/faults.hh\"\n\nnamespace X86ISA\n{\n \/\/ Base class for all x86 \"faults\" where faults is in the m5 sense\n class X86FaultBase : public FaultBase\n {\n protected:\n const char * faultName;\n const char * mnem;\n uint64_t errorCode;\n\n X86FaultBase(const char * _faultName, const char * _mnem,\n uint64_t _errorCode = 0) :\n faultName(_faultName), mnem(_mnem), errorCode(_errorCode)\n {\n }\n\n const char * name() const\n {\n return faultName;\n }\n\n virtual bool isBenign()\n {\n return true;\n }\n\n virtual const char * mnemonic() const\n {\n return mnem;\n }\n };\n\n \/\/ Base class for x86 faults which behave as if the underlying instruction\n \/\/ didn't happen.\n class X86Fault : public X86FaultBase\n {\n protected:\n X86Fault(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n };\n\n \/\/ Base class for x86 traps which behave as if the underlying instruction\n \/\/ completed.\n class X86Trap : public X86FaultBase\n {\n protected:\n X86Trap(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n \/\/ Base class for x86 aborts which seem to be catastrophic failures.\n class X86Abort : public X86FaultBase\n {\n protected:\n X86Abort(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n \/\/ Base class for x86 interrupts.\n class X86Interrupt : public X86FaultBase\n {\n protected:\n X86Interrupt(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n class UnimpInstFault : public FaultBase\n {\n public:\n const char * name() const\n {\n return \"unimplemented_micro\";\n }\n\n void invoke(ThreadContext * tc)\n {\n panic(\"Unimplemented instruction!\");\n }\n };\n\n static inline Fault genMachineCheckFault()\n {\n panic(\"Machine check fault not implemented in x86!\\n\");\n }\n\n \/\/ Below is a summary of the interrupt\/exception information in the\n \/\/ architecture manuals.\n\n \/\/ Class | Type | vector | Cause | mnem\n \/\/------------------------------------------------------------------------\n \/\/Contrib Fault 0 Divide-by-Zero-Error #DE\n \/\/Benign Either 1 Debug #DB\n \/\/Benign Interrupt 2 Non-Maskable-Interrupt #NMI\n \/\/Benign Trap 3 Breakpoint #BP\n \/\/Benign Trap 4 Overflow #OF\n \/\/Benign Fault 5 Bound-Range #BR\n \/\/Benign Fault 6 Invalid-Opcode #UD\n \/\/Benign Fault 7 Device-Not-Available #NM\n \/\/Benign Abort 8 Double-Fault #DF\n \/\/ 9 Coprocessor-Segment-Overrun\n \/\/Contrib Fault 10 Invalid-TSS #TS\n \/\/Contrib Fault 11 Segment-Not-Present #NP\n \/\/Contrib Fault 12 Stack #SS\n \/\/Contrib Fault 13 General-Protection #GP\n \/\/Either Fault 14 Page-Fault #PF\n \/\/ 15 Reserved\n \/\/Benign Fault 16 x87 Floating-Point Exception Pending #MF\n \/\/Benign Fault 17 Alignment-Check #AC\n \/\/Benign Abort 18 Machine-Check #MC\n \/\/Benign Fault 19 SIMD Floating-Point #XF\n \/\/ 20-29 Reserved\n \/\/Contrib ? 30 Security Exception #SX\n \/\/ 31 Reserved\n \/\/Benign Interrupt 0-255 External Interrupts #INTR\n \/\/Benign Interrupt 0-255 Software Interrupts INTn\n\n class DivideByZero : public X86Fault\n {\n public:\n DivideByZero() :\n X86Fault(\"Divide-by-Zero-Error\", \"#DE\")\n {}\n };\n\n class DebugException : public X86FaultBase\n {\n public:\n DebugException() :\n X86FaultBase(\"Debug\", \"#DB\")\n {}\n };\n\n class NonMaskableInterrupt : public X86Interrupt\n {\n public:\n NonMaskableInterrupt() :\n X86Interrupt(\"Non-Maskable-Interrupt\", \"#NMI\")\n {}\n };\n\n class Breakpoint : public X86Trap\n {\n public:\n Breakpoint() :\n X86Trap(\"Breakpoint\", \"#BP\")\n {}\n };\n\n class OverflowTrap : public X86Trap\n {\n public:\n OverflowTrap() :\n X86Trap(\"Overflow\", \"#OF\")\n {}\n };\n\n class BoundRange : public X86Fault\n {\n public:\n BoundRange() :\n X86Fault(\"Bound-Range\", \"#BR\")\n {}\n };\n\n class InvalidOpcode : public X86Fault\n {\n public:\n InvalidOpcode() :\n X86Fault(\"Invalid-Opcode\", \"#UD\")\n {}\n };\n\n class DeviceNotAvailable : public X86Fault\n {\n public:\n DeviceNotAvailable() :\n X86Fault(\"Device-Not-Available\", \"#NM\")\n {}\n };\n\n class DoubleFault : public X86Abort\n {\n public:\n DoubleFault() :\n X86Abort(\"Double-Fault\", \"#DF\")\n {}\n };\n\n class InvalidTSS : public X86Fault\n {\n public:\n InvalidTSS() :\n X86Fault(\"Invalid-TSS\", \"#TS\")\n {}\n };\n\n class SegmentNotPresent : public X86Fault\n {\n public:\n SegmentNotPresent() :\n X86Fault(\"Segment-Not-Present\", \"#NP\")\n {}\n };\n\n class StackFault : public X86Fault\n {\n public:\n StackFault() :\n X86Fault(\"Stack\", \"#SS\")\n {}\n };\n\n class GeneralProtection : public X86Fault\n {\n public:\n GeneralProtection(uint64_t _errorCode) :\n X86Fault(\"General-Protection\", \"#GP\", _errorCode)\n {}\n };\n\n class PageFault : public X86Fault\n {\n public:\n PageFault() :\n X86Fault(\"Page-Fault\", \"#PF\")\n {}\n };\n\n class X87FpExceptionPending : public X86Fault\n {\n public:\n X87FpExceptionPending() :\n X86Fault(\"x87 Floating-Point Exception Pending\", \"#MF\")\n {}\n };\n\n class AlignmentCheck : X86Fault\n {\n public:\n AlignmentCheck() :\n X86Fault(\"Alignment-Check\", \"#AC\")\n {}\n };\n\n class MachineCheck : X86Abort\n {\n public:\n MachineCheck() :\n X86Abort(\"Machine-Check\", \"#MC\")\n {}\n };\n\n class SIMDFloatingPointFault : X86Fault\n {\n public:\n SIMDFloatingPointFault() :\n X86Fault(\"SIMD Floating-Point\", \"#XF\")\n {}\n };\n\n class SecurityException : X86FaultBase\n {\n public:\n SecurityException() :\n X86FaultBase(\"Security Exception\", \"#SX\")\n {}\n };\n\n class ExternalInterrupt : X86Interrupt\n {\n public:\n ExternalInterrupt() :\n X86Interrupt(\"External Interrupt\", \"#INTR\")\n {}\n };\n\n class SoftwareInterrupt : X86Interrupt\n {\n public:\n SoftwareInterrupt() :\n X86Interrupt(\"Software Interrupt\", \"INTn\")\n {}\n };\n\n \/\/ These faults aren't part of the ISA definition. They trigger filling\n \/\/ the tlb on a miss and are to take the place of a hardware table walker.\n class FakeITLBFault : public X86Fault\n {\n protected:\n Addr vaddr;\n public:\n FakeITLBFault(Addr _vaddr) :\n X86Fault(\"fake instruction tlb fault\", \"itlb\"),\n vaddr(_vaddr)\n {}\n\n void invoke(ThreadContext * tc);\n };\n\n class FakeDTLBFault : public X86Fault\n {\n protected:\n Addr vaddr;\n public:\n FakeDTLBFault(Addr _vaddr) :\n X86Fault(\"fake data tlb fault\", \"dtlb\"),\n vaddr(_vaddr)\n {}\n\n void invoke(ThreadContext * tc);\n };\n};\n\n#endif \/\/ __ARCH_X86_FAULTS_HH__\nX86: Make the bases for x86 fault class public.\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#ifndef __ARCH_X86_FAULTS_HH__\n#define __ARCH_X86_FAULTS_HH__\n\n#include \"base\/misc.hh\"\n#include \"sim\/faults.hh\"\n\nnamespace X86ISA\n{\n \/\/ Base class for all x86 \"faults\" where faults is in the m5 sense\n class X86FaultBase : public FaultBase\n {\n protected:\n const char * faultName;\n const char * mnem;\n uint64_t errorCode;\n\n X86FaultBase(const char * _faultName, const char * _mnem,\n uint64_t _errorCode = 0) :\n faultName(_faultName), mnem(_mnem), errorCode(_errorCode)\n {\n }\n\n const char * name() const\n {\n return faultName;\n }\n\n virtual bool isBenign()\n {\n return true;\n }\n\n virtual const char * mnemonic() const\n {\n return mnem;\n }\n };\n\n \/\/ Base class for x86 faults which behave as if the underlying instruction\n \/\/ didn't happen.\n class X86Fault : public X86FaultBase\n {\n protected:\n X86Fault(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n };\n\n \/\/ Base class for x86 traps which behave as if the underlying instruction\n \/\/ completed.\n class X86Trap : public X86FaultBase\n {\n protected:\n X86Trap(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n \/\/ Base class for x86 aborts which seem to be catastrophic failures.\n class X86Abort : public X86FaultBase\n {\n protected:\n X86Abort(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n \/\/ Base class for x86 interrupts.\n class X86Interrupt : public X86FaultBase\n {\n protected:\n X86Interrupt(const char * name, const char * mnem,\n uint64_t _errorCode = 0) :\n X86FaultBase(name, mnem, _errorCode)\n {}\n\n#if FULL_SYSTEM\n void invoke(ThreadContext * tc);\n#endif\n };\n\n class UnimpInstFault : public FaultBase\n {\n public:\n const char * name() const\n {\n return \"unimplemented_micro\";\n }\n\n void invoke(ThreadContext * tc)\n {\n panic(\"Unimplemented instruction!\");\n }\n };\n\n static inline Fault genMachineCheckFault()\n {\n panic(\"Machine check fault not implemented in x86!\\n\");\n }\n\n \/\/ Below is a summary of the interrupt\/exception information in the\n \/\/ architecture manuals.\n\n \/\/ Class | Type | vector | Cause | mnem\n \/\/------------------------------------------------------------------------\n \/\/Contrib Fault 0 Divide-by-Zero-Error #DE\n \/\/Benign Either 1 Debug #DB\n \/\/Benign Interrupt 2 Non-Maskable-Interrupt #NMI\n \/\/Benign Trap 3 Breakpoint #BP\n \/\/Benign Trap 4 Overflow #OF\n \/\/Benign Fault 5 Bound-Range #BR\n \/\/Benign Fault 6 Invalid-Opcode #UD\n \/\/Benign Fault 7 Device-Not-Available #NM\n \/\/Benign Abort 8 Double-Fault #DF\n \/\/ 9 Coprocessor-Segment-Overrun\n \/\/Contrib Fault 10 Invalid-TSS #TS\n \/\/Contrib Fault 11 Segment-Not-Present #NP\n \/\/Contrib Fault 12 Stack #SS\n \/\/Contrib Fault 13 General-Protection #GP\n \/\/Either Fault 14 Page-Fault #PF\n \/\/ 15 Reserved\n \/\/Benign Fault 16 x87 Floating-Point Exception Pending #MF\n \/\/Benign Fault 17 Alignment-Check #AC\n \/\/Benign Abort 18 Machine-Check #MC\n \/\/Benign Fault 19 SIMD Floating-Point #XF\n \/\/ 20-29 Reserved\n \/\/Contrib ? 30 Security Exception #SX\n \/\/ 31 Reserved\n \/\/Benign Interrupt 0-255 External Interrupts #INTR\n \/\/Benign Interrupt 0-255 Software Interrupts INTn\n\n class DivideByZero : public X86Fault\n {\n public:\n DivideByZero() :\n X86Fault(\"Divide-by-Zero-Error\", \"#DE\")\n {}\n };\n\n class DebugException : public X86FaultBase\n {\n public:\n DebugException() :\n X86FaultBase(\"Debug\", \"#DB\")\n {}\n };\n\n class NonMaskableInterrupt : public X86Interrupt\n {\n public:\n NonMaskableInterrupt() :\n X86Interrupt(\"Non-Maskable-Interrupt\", \"#NMI\")\n {}\n };\n\n class Breakpoint : public X86Trap\n {\n public:\n Breakpoint() :\n X86Trap(\"Breakpoint\", \"#BP\")\n {}\n };\n\n class OverflowTrap : public X86Trap\n {\n public:\n OverflowTrap() :\n X86Trap(\"Overflow\", \"#OF\")\n {}\n };\n\n class BoundRange : public X86Fault\n {\n public:\n BoundRange() :\n X86Fault(\"Bound-Range\", \"#BR\")\n {}\n };\n\n class InvalidOpcode : public X86Fault\n {\n public:\n InvalidOpcode() :\n X86Fault(\"Invalid-Opcode\", \"#UD\")\n {}\n };\n\n class DeviceNotAvailable : public X86Fault\n {\n public:\n DeviceNotAvailable() :\n X86Fault(\"Device-Not-Available\", \"#NM\")\n {}\n };\n\n class DoubleFault : public X86Abort\n {\n public:\n DoubleFault() :\n X86Abort(\"Double-Fault\", \"#DF\")\n {}\n };\n\n class InvalidTSS : public X86Fault\n {\n public:\n InvalidTSS() :\n X86Fault(\"Invalid-TSS\", \"#TS\")\n {}\n };\n\n class SegmentNotPresent : public X86Fault\n {\n public:\n SegmentNotPresent() :\n X86Fault(\"Segment-Not-Present\", \"#NP\")\n {}\n };\n\n class StackFault : public X86Fault\n {\n public:\n StackFault() :\n X86Fault(\"Stack\", \"#SS\")\n {}\n };\n\n class GeneralProtection : public X86Fault\n {\n public:\n GeneralProtection(uint64_t _errorCode) :\n X86Fault(\"General-Protection\", \"#GP\", _errorCode)\n {}\n };\n\n class PageFault : public X86Fault\n {\n public:\n PageFault() :\n X86Fault(\"Page-Fault\", \"#PF\")\n {}\n };\n\n class X87FpExceptionPending : public X86Fault\n {\n public:\n X87FpExceptionPending() :\n X86Fault(\"x87 Floating-Point Exception Pending\", \"#MF\")\n {}\n };\n\n class AlignmentCheck : public X86Fault\n {\n public:\n AlignmentCheck() :\n X86Fault(\"Alignment-Check\", \"#AC\")\n {}\n };\n\n class MachineCheck : public X86Abort\n {\n public:\n MachineCheck() :\n X86Abort(\"Machine-Check\", \"#MC\")\n {}\n };\n\n class SIMDFloatingPointFault : public X86Fault\n {\n public:\n SIMDFloatingPointFault() :\n X86Fault(\"SIMD Floating-Point\", \"#XF\")\n {}\n };\n\n class SecurityException : public X86FaultBase\n {\n public:\n SecurityException() :\n X86FaultBase(\"Security Exception\", \"#SX\")\n {}\n };\n\n class ExternalInterrupt : public X86Interrupt\n {\n public:\n ExternalInterrupt() :\n X86Interrupt(\"External Interrupt\", \"#INTR\")\n {}\n };\n\n class SoftwareInterrupt : public X86Interrupt\n {\n public:\n SoftwareInterrupt() :\n X86Interrupt(\"Software Interrupt\", \"INTn\")\n {}\n };\n\n \/\/ These faults aren't part of the ISA definition. They trigger filling\n \/\/ the tlb on a miss and are to take the place of a hardware table walker.\n class FakeITLBFault : public X86Fault\n {\n protected:\n Addr vaddr;\n public:\n FakeITLBFault(Addr _vaddr) :\n X86Fault(\"fake instruction tlb fault\", \"itlb\"),\n vaddr(_vaddr)\n {}\n\n void invoke(ThreadContext * tc);\n };\n\n class FakeDTLBFault : public X86Fault\n {\n protected:\n Addr vaddr;\n public:\n FakeDTLBFault(Addr _vaddr) :\n X86Fault(\"fake data tlb fault\", \"dtlb\"),\n vaddr(_vaddr)\n {}\n\n void invoke(ThreadContext * tc);\n };\n};\n\n#endif \/\/ __ARCH_X86_FAULTS_HH__\n<|endoftext|>"} {"text":"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"tuple.h\"\r\n#include \"threedee.h\"\r\n#include \"matrix44.h\"\r\n#include \"hashstring.h\"\r\n#include \"locator.h\"\r\n#include \"servicecounter.h\"\r\n#include \"service.h\"\r\n#include \"servicecheckout.h\"\r\n#include \"serviceregistry.h\"\r\n#include \"image.h\"\r\n#include \"texture.h\"\r\n#include \"shader.h\"\r\n#include \"program.h\"\r\n#include \"buffer.h\"\r\n#include \"renderstate.h\"\r\n#include \r\n\r\nusing namespace venk;\r\n\r\nconst int screen_width = 640;\r\nconst int screen_height = 480;\r\n\r\nGLuint gVBO = 0; \r\nGLuint gIBO = 0;\r\n\r\nvoid render_texture(SDL_Texture *tex, SDL_Renderer* ren, int x, int y)\r\n{\r\n SDL_Rect dst;\r\n dst.x = x;\r\n dst.y = y;\r\n SDL_QueryTexture(tex, nullptr, nullptr, &dst.w, &dst.h);\r\n SDL_RenderCopy(ren, tex, NULL, &dst);\r\n}\r\n\r\nusing bufferPair_t = std::pair< std::shared_ptr, std::shared_ptr >;\r\n\r\nbufferPair_t init_buffers()\r\n{\r\n\t\/*\r\n\t * Data used to seed our vertex array and element array buffers:\r\n\t *\/\r\n\tstatic const GLfloat testVertices[] = {\r\n\t\t-1.0f, -1.0f,\r\n\t\t1.0f, -1.0f,\r\n\t\t-1.0f, 1.0f,\r\n\t\t1.0f, 1.0f\r\n\t};\r\n\r\n\tstatic const GLushort testElements[] = { 0, 1, 2, 3 };\r\n\r\n\tServiceCheckout buffers;\r\n\t\r\n\tauto vb = buffers->make_buffer(GL_ARRAY_BUFFER, (const void*) testVertices, GL_FLOAT, 4, 2, GL_STATIC_DRAW);\r\n\tauto ib = buffers->make_buffer(GL_ELEMENT_ARRAY_BUFFER, (const void*) testElements, GL_UNSIGNED_SHORT, 4, 1, GL_STATIC_DRAW);\r\n\tbufferPair_t result = make_pair(vb, ib);\r\n\treturn result;\r\n}\r\n\r\nvoid render(SDL_Window* window, SDL_Renderer* renderer, Texture* texture, Program *simple, bufferPair_t buffers)\r\n{\r\n\t(void) renderer;\r\n\t\/\/ Clear the color and depth buffers\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\r\n\tsimple->use();\r\n\ttexture->select();\r\n\tsimple->setUniformSampler(\"textureMap\", 0, texture);\r\n\tauto vb = buffers.first;\r\n\tauto ib = buffers.second;\r\n\tvb->bindAttribute(simple, \"vVertex\");\r\n\tib->bindIndices();\r\n\tib->draw();\r\n\tib->unbindIndices();\r\n\tvb->unbindAttribute(simple, \"vVertex\");\r\n\ttexture->deselect();\r\n\tsimple->unUse();\r\n\tSDL_GL_SwapWindow(window);\r\n\tSDL_Delay(5000);\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\r\n\t(void) argc;\r\n\t(void) argv;\r\n if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {\r\n\t\tstd::cerr << \"SDL_Init error: \" << SDL_GetError() << std::endl;\r\n\t\treturn 1;\r\n } else {\r\n\t\r\n\t\tSDL_SetHint( SDL_HINT_RENDER_DRIVER, \"opengl\" );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); \r\n\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\r\n\t\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\r\n\t\t\r\n\t\tstd::cout << \"Resource path is: \" << getResourcePath() << std::endl;\r\n\r\n\t\tauto window_deleter = [] (SDL_Window *w) {\r\n\t\t\tif (w) SDL_DestroyWindow(w);\r\n\t\t};\r\n\t\tstd::shared_ptr window(SDL_CreateWindow( \"SDLSkeleton\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t screen_width, screen_height,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL),\r\n\t\t\t\t\t\t\t\t\t\t window_deleter );\r\n\t\tif (!window) {\r\n\t\t\tstd::cerr << \"Unable to create SDL_Window\" << std::endl;\r\n\t\t} else {\r\n\t\t\tauto renderer_deleter = [](SDL_Renderer *r) {\r\n\t\t\t\tif (r) SDL_DestroyRenderer(r);\r\n\t\t\t};\r\n\t\t\tUint32 n_drivers = SDL_GetNumRenderDrivers();\r\n\t\t\tstd::cout << n_drivers << \" render drivers available\" << std::endl;\r\n\t\t\tfor(Uint32 i = 0; i < n_drivers; i++) {\r\n\t\t\t\tSDL_RendererInfo info;\r\n\t\t\t\tSDL_GetRenderDriverInfo(i, &info);\r\n\t\t\t\tstd::cout << i << \" \" << info.name << std::endl;\r\n\t\t\t}\r\n\t\t\tUint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE;\r\n\t\t\tstd::shared_ptr renderer(SDL_CreateRenderer(window.get(), -1, flags), renderer_deleter);\r\n\t\t\tif (renderer) {\r\n\t\t\t\t\r\n\t\t\t\tSDL_RendererInfo info;\r\n\t\t\t\tSDL_GetRendererInfo(renderer.get(), &info);\r\n\t\t\t\tstd::cout << \" Renderer chosen \" << info.name << std::endl;\r\n\t\r\n\t\t\t\tSDL_GLContext glctx = SDL_GL_CreateContext(window.get());\r\n\t\t\t\tSDL_assert(glctx != nullptr);\r\n\t\t\t\r\n\t\t\t\tUint32 err = glewInit();\r\n\t\t\t\tif (err != GLEW_OK) {\r\n\t\t\t\t\tstd::cerr << \"Glew init failed \" << glewGetErrorString(GLEW_VERSION) << std::endl;\r\n\t\t\t\t\tSDL_Quit();\r\n\t\t\t\t\texit(-1);\r\n\t\t\t\t}\r\n\t\t\r\n\t\t\t\tGLdouble maj = 0;\r\n\t\t\t\tglGetDoublev(GL_MAJOR_VERSION, &maj);\r\n\t\t\t\tGLdouble min = 0;\r\n\t\t\t\tglGetDoublev(GL_MINOR_VERSION, &min);\r\n\t\t\t\t\r\n\t\t\t\tstd::cout << \"OpenGL Version: \" << maj << \".\" << min << std::endl;\r\n\r\n\t\t\t\t\/\/Use Vsync\r\n\t\t\t\tif( SDL_GL_SetSwapInterval( 1 ) < 0 ) { \r\n\t\t\t\t\tstd::cerr << \"Warning: Unable to set VSync! SDL Error: \" << SDL_GetError() << std::endl;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\/\/ Enable depth testing\r\n\t\t\t\tglEnable(GL_DEPTH_TEST);\r\n\t\t\t\tglDepthFunc(GL_LEQUAL);\r\n\t\t\r\n\t\t\t\t\/\/ Set the clear color for when we re-draw the scene\r\n\t\t\t\tglClearColor(0.1, 0.1, 0.6, 1.0);\r\n\r\n\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\tServiceCheckout images;\r\n\t\t\t\tstd::shared_ptr img(images->loadImage(\"test.tga\"));\r\n\t\t\t\tif (img) {\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tServiceCheckout textures;\r\n\t\t\t\t\t\ttextures->setRenderer(renderer);\r\n\t\t\t\t\t\tstd::shared_ptr tex(textures->makeTexture(img.get(), true));\r\n\t\t\t\t\t\tServiceCheckout programs;\r\n\t\t\t\t\t\tstd::shared_ptr simple(programs->loadProgram(\"test\"));\r\n\t\t\t\t\t\tSDL_assert(simple->isValid());\t\t\t\r\n\t\t\t\t\t\t\/\/ ortho view, 100 units deep\r\n\t\t\t\t\t\tMatrix44 projection;\r\n\t\t\t\t\t\tprojection.ortho(0.0f, (float) screen_width, 0.0f, (float) screen_height, 0.0f, 100.0f);\r\n\t\t\t\t\t\tbufferPair_t buffers(init_buffers());\r\n\r\n\t\t\t\t\t\tServiceCheckout renderState;\r\n\t\t\t\t\t\t\/\/ to do - clean this up with a template make_parameter fn\r\n\t\t\t\t\t\tRenderParameter projParam;\r\n\t\t\t\t\t\tprojParam.type = eMAT4;\r\n\t\t\t\t\t\tfor(Uint32 i = 0; i < 16; i++)\r\n\t\t\t\t\t\t\tprojParam.value.mat4[i] = projection.elements[i];\r\n\t\t\t\t\t\trenderState->set(\"projection\", projParam);\r\n\t\t\t\t\t\tif (tex) {\r\n\t\t\t\t\t\t\trender(window.get(), renderer.get(), tex.get(), simple.get(), buffers);\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tstd::cerr << \"Creating texture failed\" << std::endl;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tSDL_GL_DeleteContext(glctx);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cerr << \"Loading image failed\" << std::endl;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tstd::cerr << \"Creating renderer failed\" << std::endl;\r\n\t\t\t}\r\n\t\t\tServiceRegistry::shutdown();\r\n\t\t}\r\n }\r\n SDL_Quit();\r\n return 0;\r\n}\r\nMake program quittable\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"tuple.h\"\r\n#include \"threedee.h\"\r\n#include \"matrix44.h\"\r\n#include \"hashstring.h\"\r\n#include \"locator.h\"\r\n#include \"servicecounter.h\"\r\n#include \"service.h\"\r\n#include \"servicecheckout.h\"\r\n#include \"serviceregistry.h\"\r\n#include \"image.h\"\r\n#include \"texture.h\"\r\n#include \"shader.h\"\r\n#include \"program.h\"\r\n#include \"buffer.h\"\r\n#include \"renderstate.h\"\r\n#include \r\n\r\nusing namespace venk;\r\n\r\nconst int screen_width = 640;\r\nconst int screen_height = 480;\r\n\r\nGLuint gVBO = 0; \r\nGLuint gIBO = 0;\r\n\r\nvoid render_texture(SDL_Texture *tex, SDL_Renderer* ren, int x, int y)\r\n{\r\n SDL_Rect dst;\r\n dst.x = x;\r\n dst.y = y;\r\n SDL_QueryTexture(tex, nullptr, nullptr, &dst.w, &dst.h);\r\n SDL_RenderCopy(ren, tex, NULL, &dst);\r\n}\r\n\r\nusing bufferPair_t = std::pair< std::shared_ptr, std::shared_ptr >;\r\n\r\nbufferPair_t init_buffers()\r\n{\r\n\t\/*\r\n\t * Data used to seed our vertex array and element array buffers:\r\n\t *\/\r\n\tstatic const GLfloat testVertices[] = {\r\n\t\t-1.0f, -1.0f,\r\n\t\t1.0f, -1.0f,\r\n\t\t-1.0f, 1.0f,\r\n\t\t1.0f, 1.0f\r\n\t};\r\n\r\n\tstatic const GLushort testElements[] = { 0, 1, 2, 3 };\r\n\r\n\tServiceCheckout buffers;\r\n\t\r\n\tauto vb = buffers->make_buffer(GL_ARRAY_BUFFER, (const void*) testVertices, GL_FLOAT, 4, 2, GL_STATIC_DRAW);\r\n\tauto ib = buffers->make_buffer(GL_ELEMENT_ARRAY_BUFFER, (const void*) testElements, GL_UNSIGNED_SHORT, 4, 1, GL_STATIC_DRAW);\r\n\tbufferPair_t result = make_pair(vb, ib);\r\n\treturn result;\r\n}\r\n\r\nvoid render(SDL_Window* window, SDL_Renderer* renderer, Texture* texture, Program *simple, bufferPair_t buffers)\r\n{\r\n\t(void) renderer;\r\n\t\/\/ Clear the color and depth buffers\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\r\n\tsimple->use();\r\n\ttexture->select();\r\n\tsimple->setUniformSampler(\"textureMap\", 0, texture);\r\n\tauto vb = buffers.first;\r\n\tauto ib = buffers.second;\r\n\tvb->bindAttribute(simple, \"vVertex\");\r\n\tib->bindIndices();\r\n\tib->draw();\r\n\tib->unbindIndices();\r\n\tvb->unbindAttribute(simple, \"vVertex\");\r\n\ttexture->deselect();\r\n\tsimple->unUse();\r\n\tSDL_GL_SwapWindow(window);\r\n}\r\n\r\nint main(int argc, char **argv)\r\n{\r\n\r\n\t(void) argc;\r\n\t(void) argv;\r\n if (SDL_Init(SDL_INIT_EVERYTHING) != 0) {\r\n\t\tstd::cerr << \"SDL_Init error: \" << SDL_GetError() << std::endl;\r\n\t\treturn 1;\r\n } else {\r\n\t\r\n\t\tSDL_SetHint( SDL_HINT_RENDER_DRIVER, \"opengl\" );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 3 );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 3 );\r\n\t\tSDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE ); \r\n\t\tSDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\r\n\t\tSDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);\r\n\t\t\r\n\t\tstd::cout << \"Resource path is: \" << getResourcePath() << std::endl;\r\n\r\n\t\tauto window_deleter = [] (SDL_Window *w) {\r\n\t\t\tif (w) SDL_DestroyWindow(w);\r\n\t\t};\r\n\t\tstd::shared_ptr window(SDL_CreateWindow( \"SDLSkeleton\",\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t screen_width, screen_height,\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL),\r\n\t\t\t\t\t\t\t\t\t\t window_deleter );\r\n\t\tif (!window) {\r\n\t\t\tstd::cerr << \"Unable to create SDL_Window\" << std::endl;\r\n\t\t} else {\r\n\t\t\tauto renderer_deleter = [](SDL_Renderer *r) {\r\n\t\t\t\tif (r) SDL_DestroyRenderer(r);\r\n\t\t\t};\r\n\t\t\tUint32 n_drivers = SDL_GetNumRenderDrivers();\r\n\t\t\tstd::cout << n_drivers << \" render drivers available\" << std::endl;\r\n\t\t\tfor(Uint32 i = 0; i < n_drivers; i++) {\r\n\t\t\t\tSDL_RendererInfo info;\r\n\t\t\t\tSDL_GetRenderDriverInfo(i, &info);\r\n\t\t\t\tstd::cout << i << \" \" << info.name << std::endl;\r\n\t\t\t}\r\n\t\t\tUint32 flags = SDL_RENDERER_ACCELERATED | SDL_RENDERER_TARGETTEXTURE;\r\n\t\t\tstd::shared_ptr renderer(SDL_CreateRenderer(window.get(), -1, flags), renderer_deleter);\r\n\t\t\tif (renderer) {\r\n\t\t\t\t\r\n\t\t\t\tSDL_RendererInfo info;\r\n\t\t\t\tSDL_GetRendererInfo(renderer.get(), &info);\r\n\t\t\t\tstd::cout << \" Renderer chosen \" << info.name << std::endl;\r\n\t\r\n\t\t\t\tSDL_GLContext glctx = SDL_GL_CreateContext(window.get());\r\n\t\t\t\tSDL_assert(glctx != nullptr);\r\n\t\t\t\r\n\t\t\t\tUint32 err = glewInit();\r\n\t\t\t\tif (err != GLEW_OK) {\r\n\t\t\t\t\tstd::cerr << \"Glew init failed \" << glewGetErrorString(GLEW_VERSION) << std::endl;\r\n\t\t\t\t\tSDL_Quit();\r\n\t\t\t\t\texit(-1);\r\n\t\t\t\t}\r\n\t\t\r\n\t\t\t\tGLdouble maj = 0;\r\n\t\t\t\tglGetDoublev(GL_MAJOR_VERSION, &maj);\r\n\t\t\t\tGLdouble min = 0;\r\n\t\t\t\tglGetDoublev(GL_MINOR_VERSION, &min);\r\n\t\t\t\t\r\n\t\t\t\tstd::cout << \"OpenGL Version: \" << maj << \".\" << min << std::endl;\r\n\r\n\t\t\t\t\/\/Use Vsync\r\n\t\t\t\tif( SDL_GL_SetSwapInterval( 1 ) < 0 ) { \r\n\t\t\t\t\tstd::cerr << \"Warning: Unable to set VSync! SDL Error: \" << SDL_GetError() << std::endl;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\/\/ Enable depth testing\r\n\t\t\t\tglEnable(GL_DEPTH_TEST);\r\n\t\t\t\tglDepthFunc(GL_LEQUAL);\r\n\t\t\r\n\t\t\t\t\/\/ Set the clear color for when we re-draw the scene\r\n\t\t\t\tglClearColor(0.1, 0.1, 0.6, 1.0);\r\n\r\n\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\tServiceCheckout images;\r\n\t\t\t\tstd::shared_ptr img(images->loadImage(\"test.tga\"));\r\n\t\t\t\tif (img) {\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\tServiceRegistry::initialise();\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tServiceCheckout textures;\r\n\t\t\t\t\t\ttextures->setRenderer(renderer);\r\n\t\t\t\t\t\tstd::shared_ptr tex(textures->makeTexture(img.get(), true));\r\n\t\t\t\t\t\tServiceCheckout programs;\r\n\t\t\t\t\t\tstd::shared_ptr simple(programs->loadProgram(\"test\"));\r\n\t\t\t\t\t\tSDL_assert(simple->isValid());\t\t\t\r\n\t\t\t\t\t\t\/\/ ortho view, 100 units deep\r\n\t\t\t\t\t\tMatrix44 projection;\r\n\t\t\t\t\t\tprojection.ortho(0.0f, (float) screen_width, 0.0f, (float) screen_height, 0.0f, 100.0f);\r\n\t\t\t\t\t\tbufferPair_t buffers(init_buffers());\r\n\r\n\t\t\t\t\t\tServiceCheckout renderState;\r\n\t\t\t\t\t\t\/\/ to do - clean this up with a template make_parameter fn\r\n\t\t\t\t\t\tRenderParameter projParam;\r\n\t\t\t\t\t\tprojParam.type = eMAT4;\r\n\t\t\t\t\t\tfor(Uint32 i = 0; i < 16; i++)\r\n\t\t\t\t\t\t\tprojParam.value.mat4[i] = projection.elements[i];\r\n\t\t\t\t\t\trenderState->set(\"projection\", projParam);\r\n\t\t\t\t\t\tif (tex) {\r\n\t\t\t\t\t\t\tbool quit = false;\r\n\t\t\t\t\t\t\tSDL_Event e;\r\n\t\t\t\t\t\t\twhile (!quit) {\r\n\t\t\t\t\t\t\t\t\/\/Handle events on queue \r\n\t\t\t\t\t\t\t\twhile( SDL_PollEvent( &e ) != 0 ) { \r\n\t\t\t\t\t\t\t\t\t\/\/User requests quit \r\n\t\t\t\t\t\t\t\t\tif( e.type == SDL_QUIT ) { \r\n\t\t\t\t\t\t\t\t\t\tquit = true; \r\n\t\t\t\t\t\t\t\t\t} \r\n\t\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t\t\trender(window.get(), renderer.get(), tex.get(), simple.get(), buffers);\r\n\t\t\t\t\t\t\t}\r\n\t\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\tstd::cerr << \"Creating texture failed\" << std::endl;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tServiceRegistry::shutdown();\r\n\t\t\t\t\tSDL_GL_DeleteContext(glctx);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstd::cerr << \"Loading image failed\" << std::endl;\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tstd::cerr << \"Creating renderer failed\" << std::endl;\r\n\t\t\t}\r\n\t\t\tServiceRegistry::shutdown();\r\n\t\t}\r\n }\r\n SDL_Quit();\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"connection.h\"\n#include \"emptystatement.h\"\n#include \"command.h\"\n#include \"dbmodulewrap.h\"\n#include \"utils.h\"\n\nnamespace ss {\n\ninline bool expect_row(command::ResType rt) {\n switch (rt) {\n case command::RES_ROW:\n case command::RES_PARAM:\n return true;\n default:\n return false;\n }\n}\n\n\nclass Statement : public EmptyStatement {\n QoreHashNode *_execRes;\n\n bool has_res() {\n return _execRes ? true : false;\n }\n\n void set_res(QoreHashNode *res, ExceptionSink* xsink) {\n if (_execRes) _execRes->deref(xsink);\n _execRes = res;\n }\n\n QoreHashNode * release_res() {\n QoreHashNode *rv = _execRes;\n _execRes = 0;\n return rv;\n }\n\n ~Statement() {}\n\n SafePtr context;\n Placeholders placeholders;\npublic:\n typedef connection Connection;\n\n Statement() : _execRes(0) {}\n\n static void Delete(Statement *self, ExceptionSink* xsink) {\n if (!self) return;\n self->set_res(0, xsink);\n delete self;\n }\n\n int exec(connection *conn,\n const QoreString *query,\n const QoreListNode *args,\n bool raw,\n ExceptionSink* xsink)\n {\n#ifdef _QORE_HAS_DBI_EXECRAW\n if (raw) {\n context.reset(conn->create_command(query, xsink));\n } else\n#endif\n {\n context.reset(conn->create_command(query, args, xsink));\n }\n return 0;\n }\n\n bool next(SQLStatement* stmt, ExceptionSink* xsink) {\n command::ResType res = context->read_next_result(xsink);\n if (expect_row(res)) {\n if (!has_res()) {\n set_res(context->fetch_row(xsink), xsink);\n }\n }\n\n return has_res();\n }\n\n QoreHashNode * fetch_row(SQLStatement* stmt, ExceptionSink* xsink) {\n return release_res();\n }\n\n int define(SQLStatement* stmt, ExceptionSink* xsink) {\n return 0;\n }\n\n\n QoreListNode* fetch_rows(SQLStatement* stmt, int rows,\n ExceptionSink* xsink)\n {\n int r = rows;\n ReferenceHolder reslist(xsink);\n reslist = new QoreListNode();\n\n \/\/ next was already called once\n do {\n \/\/ acording the doc rows <=0 means fetch all\n if (r > 0) {\n if (rows <= 0) break;\n rows--;\n }\n if (xsink->isException()) return 0;\n ReferenceHolder h(xsink);\n h = fetch_row(stmt, xsink);\n if (!h) continue;\n reslist->insert(h.release());\n } while (next(stmt, xsink));\n return reslist.release();\n }\n\n QoreHashNode* get_output(SQLStatement* stmt, ExceptionSink* xsink) {\n return context->read_cols(&placeholders, xsink);\n }\n\n\n int affected_rows(SQLStatement* stmt, ExceptionSink* xsink) {\n return context->get_row_count();\n }\n\n\n QoreHashNode* fetch_columns(SQLStatement* stmt, int rows, ExceptionSink* xsink) {\n return context->read_cols(0, xsink);\n }\n\n int bind_placeholders(SQLStatement* stmt,\n const QoreListNode& l,\n ExceptionSink* xsink)\n {\n placeholders.clear();\n ConstListIterator it(l);\n while (it.next()) {\n QoreValue v(it.getValue());\n QoreStringNode *s = v.get();\n placeholders.push_back(s->getBuffer());\n }\n return 0;\n }\n\n};\n\nvoid init(qore_dbi_method_list &methods) {\n DBModuleWrap module(methods);\n module.reg();\n}\n\n} \/\/ namespace ss\nsybase: SQLStatement::getAffectedRows fix#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \"connection.h\"\n#include \"emptystatement.h\"\n#include \"command.h\"\n#include \"dbmodulewrap.h\"\n#include \"utils.h\"\n\nnamespace ss {\n\ninline bool expect_row(command::ResType rt) {\n switch (rt) {\n case command::RES_ROW:\n case command::RES_PARAM:\n return true;\n default:\n return false;\n }\n}\n\n\nclass Statement : public EmptyStatement {\n QoreHashNode *_execRes;\n\n bool has_res() {\n return _execRes ? true : false;\n }\n\n void set_res(QoreHashNode *res, ExceptionSink* xsink) {\n if (_execRes) _execRes->deref(xsink);\n _execRes = res;\n }\n\n QoreHashNode * release_res() {\n QoreHashNode *rv = _execRes;\n _execRes = 0;\n return rv;\n }\n\n ~Statement() {}\n\n SafePtr context;\n Placeholders placeholders;\npublic:\n typedef connection Connection;\n\n Statement() : _execRes(0) {}\n\n static void Delete(Statement *self, ExceptionSink* xsink) {\n if (!self) return;\n self->set_res(0, xsink);\n delete self;\n }\n\n int exec(connection *conn,\n const QoreString *query,\n const QoreListNode *args,\n bool raw,\n ExceptionSink* xsink)\n {\n#ifdef _QORE_HAS_DBI_EXECRAW\n if (raw) {\n context.reset(conn->create_command(query, xsink));\n } else\n#endif\n {\n context.reset(conn->create_command(query, args, xsink));\n }\n \/\/ not sure what to do with the returned value here\n context->read_next_result(xsink);\n return 0;\n }\n\n bool next(SQLStatement* stmt, ExceptionSink* xsink) {\n command::ResType res = context->read_next_result(xsink);\n if (expect_row(res)) {\n if (!has_res()) {\n set_res(context->fetch_row(xsink), xsink);\n }\n }\n\n return has_res();\n }\n\n QoreHashNode * fetch_row(SQLStatement* stmt, ExceptionSink* xsink) {\n return release_res();\n }\n\n int define(SQLStatement* stmt, ExceptionSink* xsink) {\n return 0;\n }\n\n\n QoreListNode* fetch_rows(SQLStatement* stmt, int rows,\n ExceptionSink* xsink)\n {\n int r = rows;\n ReferenceHolder reslist(xsink);\n reslist = new QoreListNode();\n\n \/\/ next was already called once\n do {\n \/\/ acording the doc rows <=0 means fetch all\n if (r > 0) {\n if (rows <= 0) break;\n rows--;\n }\n if (xsink->isException()) return 0;\n ReferenceHolder h(xsink);\n h = fetch_row(stmt, xsink);\n if (!h) continue;\n reslist->insert(h.release());\n } while (next(stmt, xsink));\n return reslist.release();\n }\n\n QoreHashNode* get_output(SQLStatement* stmt, ExceptionSink* xsink) {\n return context->read_cols(&placeholders, xsink);\n }\n\n\n int affected_rows(SQLStatement* stmt, ExceptionSink* xsink) {\n return context->get_row_count();\n }\n\n\n QoreHashNode* fetch_columns(SQLStatement* stmt, int rows, ExceptionSink* xsink) {\n return context->read_cols(0, xsink);\n }\n\n int bind_placeholders(SQLStatement* stmt,\n const QoreListNode& l,\n ExceptionSink* xsink)\n {\n placeholders.clear();\n ConstListIterator it(l);\n while (it.next()) {\n QoreValue v(it.getValue());\n QoreStringNode *s = v.get();\n placeholders.push_back(s->getBuffer());\n }\n return 0;\n }\n};\n\nvoid init(qore_dbi_method_list &methods) {\n DBModuleWrap module(methods);\n module.reg();\n}\n\n} \/\/ namespace ss\n<|endoftext|>"} {"text":"\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"vk_test.h\"\n\nRD_TEST(VK_Mesh_Zoo, VulkanGraphicsTest)\n{\n static constexpr const char *Description = \"Draws some primitives for testing the mesh view.\";\n\n std::string common = R\"EOSHADER(\n\n#version 420 core\n\n)EOSHADER\";\n\n std::string vertex = R\"EOSHADER(\n\nlayout(location = 0) in vec3 Position;\nlayout(location = 1) in vec4 Color;\n\nlayout(push_constant, std140) uniform pushbuf\n{\n vec4 scale;\n vec4 offset;\n};\n\nlayout(location = 0) out vec2 vertOutCol2;\nlayout(location = 1) out vec4 vertOutcol;\n\nvoid main()\n{\n\tvec4 pos = vec4(Position.xy * scale.xy + offset.xy, Position.z, 1.0f);\n\tvertOutcol = Color;\n\n if(gl_InstanceIndex > 0)\n {\n pos *= 0.3f;\n pos.xy += vec2(0.1f);\n vertOutcol.x = 1.0f; \n }\n\n vertOutCol2.xy = pos.xy;\n\n\tgl_Position = pos * vec4(1, -1, 1, 1);\n#if defined(USE_POINTS)\n gl_PointSize = 1.0f;\n#endif\n}\n\n)EOSHADER\";\n\n std::string pixel = R\"EOSHADER(\n\nlayout(location = 0) in vec2 vertInCol2;\nlayout(location = 1) in vec4 vertIncol;\n\nlayout(location = 0, index = 0) out vec4 Color;\n\nvoid main()\n{\n\tColor = vertIncol + 1.0e-20 * vertInCol2.xyxy;\n}\n\n)EOSHADER\";\n\n int main()\n {\n \/\/ initialise, create window, create context, etc\n if(!Init())\n return 3;\n\n const DefaultA2V test[] = {\n \/\/ single color quad\n {Vec3f(50.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n \/\/ points, to test vertex picking\n {Vec3f(50.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n {Vec3f(70.0f, 170.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(170.0f, 170.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(70.0f, 70.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n };\n\n \/\/ create depth-stencil image\n AllocatedImage depthimg(this, vkh::ImageCreateInfo(mainWindow->scissor.extent.width,\n mainWindow->scissor.extent.height, 0,\n VK_FORMAT_D32_SFLOAT_S8_UINT,\n VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_GPU_ONLY}));\n\n VkImageView dsvview = createImageView(vkh::ImageViewCreateInfo(\n depthimg.image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_D32_SFLOAT_S8_UINT, {},\n vkh::ImageSubresourceRange(VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)));\n\n \/\/ create renderpass using the DS image\n vkh::RenderPassCreator renderPassCreateInfo;\n\n renderPassCreateInfo.attachments.push_back(vkh::AttachmentDescription(\n mainWindow->format, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL));\n renderPassCreateInfo.attachments.push_back(vkh::AttachmentDescription(\n VK_FORMAT_D32_SFLOAT_S8_UINT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,\n VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_SAMPLE_COUNT_1_BIT,\n VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE));\n\n renderPassCreateInfo.addSubpass({VkAttachmentReference({0, VK_IMAGE_LAYOUT_GENERAL})}, 1,\n VK_IMAGE_LAYOUT_GENERAL);\n\n VkRenderPass renderPass = createRenderPass(renderPassCreateInfo);\n\n \/\/ create framebuffers using swapchain images and DS image\n std::vector fbs;\n fbs.resize(mainWindow->GetCount());\n\n for(size_t i = 0; i < mainWindow->GetCount(); i++)\n fbs[i] = createFramebuffer(vkh::FramebufferCreateInfo(\n renderPass, {mainWindow->GetView(i), dsvview}, mainWindow->scissor.extent));\n\n VkPipelineLayout layout = createPipelineLayout(vkh::PipelineLayoutCreateInfo(\n {},\n {\n vkh::PushConstantRange(VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Vec4f) * 2),\n }));\n\n vkh::GraphicsPipelineCreateInfo pipeCreateInfo;\n\n pipeCreateInfo.layout = layout;\n pipeCreateInfo.renderPass = renderPass;\n\n pipeCreateInfo.vertexInputState.vertexBindingDescriptions = {vkh::vertexBind(0, DefaultA2V)};\n pipeCreateInfo.vertexInputState.vertexAttributeDescriptions = {\n vkh::vertexAttr(0, 0, DefaultA2V, pos), vkh::vertexAttr(1, 0, DefaultA2V, col),\n vkh::vertexAttr(2, 0, DefaultA2V, uv),\n };\n\n pipeCreateInfo.stages = {\n CompileShaderModule(common + vertex, ShaderLang::glsl, ShaderStage::vert, \"main\"),\n CompileShaderModule(common + pixel, ShaderLang::glsl, ShaderStage::frag, \"main\"),\n };\n\n pipeCreateInfo.depthStencilState.depthTestEnable = VK_TRUE;\n pipeCreateInfo.depthStencilState.depthWriteEnable = VK_TRUE;\n pipeCreateInfo.depthStencilState.stencilTestEnable = VK_FALSE;\n pipeCreateInfo.depthStencilState.back = pipeCreateInfo.depthStencilState.front;\n\n VkPipeline pipe = createGraphicsPipeline(pipeCreateInfo);\n\n pipeCreateInfo.stages[0] = CompileShaderModule(common + \"\\n#define USE_POINTS\\n\" + vertex,\n ShaderLang::glsl, ShaderStage::vert, \"main\"),\n pipeCreateInfo.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;\n\n VkPipeline pointspipe = createGraphicsPipeline(pipeCreateInfo);\n\n pipeCreateInfo.vertexInputState.vertexBindingDescriptions = {{0, 0, VK_VERTEX_INPUT_RATE_VERTEX}};\n\n VkPipeline stride0pipe = createGraphicsPipeline(pipeCreateInfo);\n\n AllocatedBuffer vb(this,\n vkh::BufferCreateInfo(sizeof(test), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |\n VK_BUFFER_USAGE_TRANSFER_DST_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_CPU_TO_GPU}));\n\n vb.upload(test);\n\n Vec4f cbufferdata[] = {\n Vec4f(2.0f \/ (float)screenWidth, 2.0f \/ (float)screenHeight, 1.0f, 1.0f),\n Vec4f(-1.0f, -1.0f, 0.0f, 0.0f),\n };\n\n AllocatedBuffer cb(\n this, vkh::BufferCreateInfo(sizeof(cbufferdata), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |\n VK_BUFFER_USAGE_TRANSFER_DST_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_CPU_TO_GPU}));\n\n cb.upload(cbufferdata);\n\n while(Running())\n {\n VkCommandBuffer cmd = GetCommandBuffer();\n\n vkBeginCommandBuffer(cmd, vkh::CommandBufferBeginInfo());\n\n VkImage swapimg =\n StartUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n vkCmdClearColorImage(cmd, swapimg, VK_IMAGE_LAYOUT_GENERAL,\n vkh::ClearColorValue(0.2f, 0.2f, 0.2f, 1.0f), 1,\n vkh::ImageSubresourceRange());\n\n vkCmdBeginRenderPass(\n cmd, vkh::RenderPassBeginInfo(renderPass, fbs[mainWindow->imgIndex], mainWindow->scissor,\n {{}, vkh::ClearValue(1.0f, 0)}),\n VK_SUBPASS_CONTENTS_INLINE);\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);\n vkCmdPushConstants(cmd, layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(cbufferdata),\n &cbufferdata);\n vkCmdSetViewport(cmd, 0, 1, &mainWindow->viewport);\n vkCmdSetScissor(cmd, 0, 1, &mainWindow->scissor);\n vkh::cmdBindVertexBuffers(cmd, 0, {vb.buffer}, {0});\n\n vkCmdDraw(cmd, 3, 1, 10, 0);\n\n setMarker(cmd, \"Quad\");\n\n vkCmdDraw(cmd, 6, 2, 0, 0);\n\n setMarker(cmd, \"Points\");\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pointspipe);\n\n vkCmdDraw(cmd, 4, 1, 6, 0);\n\n setMarker(cmd, \"Stride 0\");\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, stride0pipe);\n\n vkCmdDraw(cmd, 1, 1, 0, 0);\n\n vkCmdEndRenderPass(cmd);\n\n FinishUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n vkEndCommandBuffer(cmd);\n\n Submit(0, 1, {cmd});\n\n Present();\n }\n\n return 0;\n }\n};\n\nREGISTER_TEST();\nTest push constant range that applies to vertex and fragment stages\/******************************************************************************\n * The MIT License (MIT)\n *\n * Copyright (c) 2019-2020 Baldur Karlsson\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n ******************************************************************************\/\n\n#include \"vk_test.h\"\n\nRD_TEST(VK_Mesh_Zoo, VulkanGraphicsTest)\n{\n static constexpr const char *Description = \"Draws some primitives for testing the mesh view.\";\n\n std::string common = R\"EOSHADER(\n\n#version 420 core\n\n)EOSHADER\";\n\n std::string vertex = R\"EOSHADER(\n\nlayout(location = 0) in vec3 Position;\nlayout(location = 1) in vec4 Color;\n\nlayout(push_constant, std140) uniform pushbuf\n{\n vec4 scale;\n vec4 offset;\n};\n\nlayout(location = 0) out vec2 vertOutCol2;\nlayout(location = 1) out vec4 vertOutcol;\n\nvoid main()\n{\n\tvec4 pos = vec4(Position.xy * scale.xy + offset.xy, Position.z, 1.0f);\n\tvertOutcol = Color;\n\n if(gl_InstanceIndex > 0)\n {\n pos *= 0.3f;\n pos.xy += vec2(0.1f);\n vertOutcol.x = 1.0f; \n }\n\n vertOutCol2.xy = pos.xy;\n\n\tgl_Position = pos * vec4(1, -1, 1, 1);\n#if defined(USE_POINTS)\n gl_PointSize = 1.0f;\n#endif\n}\n\n)EOSHADER\";\n\n std::string pixel = R\"EOSHADER(\n\nlayout(location = 0) in vec2 vertInCol2;\nlayout(location = 1) in vec4 vertIncol;\n\nlayout(location = 0, index = 0) out vec4 Color;\n\nvoid main()\n{\n\tColor = vertIncol + 1.0e-20 * vertInCol2.xyxy;\n}\n\n)EOSHADER\";\n\n int main()\n {\n \/\/ initialise, create window, create context, etc\n if(!Init())\n return 3;\n\n const DefaultA2V test[] = {\n \/\/ single color quad\n {Vec3f(50.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n \/\/ points, to test vertex picking\n {Vec3f(50.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 250.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(250.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(50.0f, 50.0f, 0.2f), Vec4f(0.0f, 1.0f, 0.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n\n {Vec3f(70.0f, 170.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(170.0f, 170.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n {Vec3f(70.0f, 70.0f, 0.1f), Vec4f(1.0f, 0.0f, 1.0f, 1.0f), Vec2f(0.0f, 0.0f)},\n };\n\n \/\/ create depth-stencil image\n AllocatedImage depthimg(this, vkh::ImageCreateInfo(mainWindow->scissor.extent.width,\n mainWindow->scissor.extent.height, 0,\n VK_FORMAT_D32_SFLOAT_S8_UINT,\n VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_GPU_ONLY}));\n\n VkImageView dsvview = createImageView(vkh::ImageViewCreateInfo(\n depthimg.image, VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_D32_SFLOAT_S8_UINT, {},\n vkh::ImageSubresourceRange(VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)));\n\n \/\/ create renderpass using the DS image\n vkh::RenderPassCreator renderPassCreateInfo;\n\n renderPassCreateInfo.attachments.push_back(vkh::AttachmentDescription(\n mainWindow->format, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL));\n renderPassCreateInfo.attachments.push_back(vkh::AttachmentDescription(\n VK_FORMAT_D32_SFLOAT_S8_UINT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL,\n VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_SAMPLE_COUNT_1_BIT,\n VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE));\n\n renderPassCreateInfo.addSubpass({VkAttachmentReference({0, VK_IMAGE_LAYOUT_GENERAL})}, 1,\n VK_IMAGE_LAYOUT_GENERAL);\n\n VkRenderPass renderPass = createRenderPass(renderPassCreateInfo);\n\n \/\/ create framebuffers using swapchain images and DS image\n std::vector fbs;\n fbs.resize(mainWindow->GetCount());\n\n for(size_t i = 0; i < mainWindow->GetCount(); i++)\n fbs[i] = createFramebuffer(vkh::FramebufferCreateInfo(\n renderPass, {mainWindow->GetView(i), dsvview}, mainWindow->scissor.extent));\n\n VkPipelineLayout layout = createPipelineLayout(vkh::PipelineLayoutCreateInfo(\n {},\n {\n vkh::PushConstantRange(VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,\n sizeof(Vec4f) * 2),\n }));\n\n VkPipelineLayout layout2 = createPipelineLayout(vkh::PipelineLayoutCreateInfo(\n {},\n {\n vkh::PushConstantRange(VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(Vec4f) * 2),\n }));\n\n vkh::GraphicsPipelineCreateInfo pipeCreateInfo;\n\n pipeCreateInfo.layout = layout;\n pipeCreateInfo.renderPass = renderPass;\n\n pipeCreateInfo.vertexInputState.vertexBindingDescriptions = {vkh::vertexBind(0, DefaultA2V)};\n pipeCreateInfo.vertexInputState.vertexAttributeDescriptions = {\n vkh::vertexAttr(0, 0, DefaultA2V, pos), vkh::vertexAttr(1, 0, DefaultA2V, col),\n vkh::vertexAttr(2, 0, DefaultA2V, uv),\n };\n\n pipeCreateInfo.stages = {\n CompileShaderModule(common + vertex, ShaderLang::glsl, ShaderStage::vert, \"main\"),\n CompileShaderModule(common + pixel, ShaderLang::glsl, ShaderStage::frag, \"main\"),\n };\n\n pipeCreateInfo.depthStencilState.depthTestEnable = VK_TRUE;\n pipeCreateInfo.depthStencilState.depthWriteEnable = VK_TRUE;\n pipeCreateInfo.depthStencilState.stencilTestEnable = VK_FALSE;\n pipeCreateInfo.depthStencilState.back = pipeCreateInfo.depthStencilState.front;\n\n VkPipeline pipe = createGraphicsPipeline(pipeCreateInfo);\n\n pipeCreateInfo.stages[0] = CompileShaderModule(common + \"\\n#define USE_POINTS\\n\" + vertex,\n ShaderLang::glsl, ShaderStage::vert, \"main\"),\n pipeCreateInfo.inputAssemblyState.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;\n\n VkPipeline pointspipe = createGraphicsPipeline(pipeCreateInfo);\n\n pipeCreateInfo.vertexInputState.vertexBindingDescriptions = {{0, 0, VK_VERTEX_INPUT_RATE_VERTEX}};\n\n pipeCreateInfo.layout = layout2;\n\n VkPipeline stride0pipe = createGraphicsPipeline(pipeCreateInfo);\n\n AllocatedBuffer vb(this,\n vkh::BufferCreateInfo(sizeof(test), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |\n VK_BUFFER_USAGE_TRANSFER_DST_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_CPU_TO_GPU}));\n\n vb.upload(test);\n\n Vec4f cbufferdata[] = {\n Vec4f(2.0f \/ (float)screenWidth, 2.0f \/ (float)screenHeight, 1.0f, 1.0f),\n Vec4f(-1.0f, -1.0f, 0.0f, 0.0f),\n };\n\n AllocatedBuffer cb(\n this, vkh::BufferCreateInfo(sizeof(cbufferdata), VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT |\n VK_BUFFER_USAGE_TRANSFER_DST_BIT),\n VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_CPU_TO_GPU}));\n\n cb.upload(cbufferdata);\n\n while(Running())\n {\n VkCommandBuffer cmd = GetCommandBuffer();\n\n vkBeginCommandBuffer(cmd, vkh::CommandBufferBeginInfo());\n\n VkImage swapimg =\n StartUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n vkCmdClearColorImage(cmd, swapimg, VK_IMAGE_LAYOUT_GENERAL,\n vkh::ClearColorValue(0.2f, 0.2f, 0.2f, 1.0f), 1,\n vkh::ImageSubresourceRange());\n\n vkCmdBeginRenderPass(\n cmd, vkh::RenderPassBeginInfo(renderPass, fbs[mainWindow->imgIndex], mainWindow->scissor,\n {{}, vkh::ClearValue(1.0f, 0)}),\n VK_SUBPASS_CONTENTS_INLINE);\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);\n vkCmdPushConstants(cmd, layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,\n sizeof(cbufferdata), &cbufferdata);\n vkCmdSetViewport(cmd, 0, 1, &mainWindow->viewport);\n vkCmdSetScissor(cmd, 0, 1, &mainWindow->scissor);\n vkh::cmdBindVertexBuffers(cmd, 0, {vb.buffer}, {0});\n\n vkCmdDraw(cmd, 3, 1, 10, 0);\n\n setMarker(cmd, \"Quad\");\n\n vkCmdDraw(cmd, 6, 2, 0, 0);\n\n setMarker(cmd, \"Points\");\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pointspipe);\n\n vkCmdDraw(cmd, 4, 1, 6, 0);\n\n setMarker(cmd, \"Stride 0\");\n\n vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, stride0pipe);\n vkCmdPushConstants(cmd, layout2, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(cbufferdata),\n &cbufferdata);\n\n vkCmdDraw(cmd, 1, 1, 0, 0);\n\n vkCmdEndRenderPass(cmd);\n\n FinishUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);\n\n vkEndCommandBuffer(cmd);\n\n Submit(0, 1, {cmd});\n\n Present();\n }\n\n return 0;\n }\n};\n\nREGISTER_TEST();\n<|endoftext|>"} {"text":"\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n\/\/ This module\n#include \"ParameterXML.h\"\n\/\/ This application\n#include \"ConfigFile.h\"\n\/\/ The Qt library\n#include \n#include \n#include \n\/\/ The C++ Standard Library\n#include \n\nQString const ParameterXML::XML_TAG = \"parameter\";\n\nParameterXML::ParameterXML(QDomNode const& _node,\n\t\t\t QTreeWidgetItem * _parentItem,\n\t\t\t QTreeWidgetItem * _pre,\n\t\t\t QObject * _parent,\n\t\t\t const char * _name) :\n Super(_node, _parentItem, _pre, _parent, _name),\n config_(ConfigFile::instance())\n{\n assert(!node().toElement().isNull());\n}\n\nParameterXML::ParameterXML(QDomNode const& _node,\n\t\t\t QTreeWidget * _view,\n\t\t\t QTreeWidgetItem * _pre,\n\t\t\t QObject * _parent,\n\t\t\t const char * _name) :\n Super(_node, _view, _pre, _parent, _name),\n config_(ConfigFile::instance())\n{\n assert(!node().toElement().isNull());\n}\n\nvoid \nParameterXML::init()\n{\n}\n\nvoid\nParameterXML::contextMenu(QMenu& _menu)\n{\n \/\/ Add 4 QActions to the context menu: \"Set Parameters\", \"Up\", \"Down\" and\n \/\/ \"Delete\"\n QAction * pAction = NULL;\n\n pAction = new QAction(tr(\"Set Parameters\"), this);\n connect(pAction, SIGNAL(triggered()), this, SLOT(slotSetParameters()));\n _menu.addAction(pAction);\n\n _menu.addSeparator();\n\n pAction = new QAction(tr(\"Up\"), this);\n connect(pAction, SIGNAL(triggered()), this, SLOT(up()));\n _menu.addAction(pAction);\n\n pAction = new QAction(tr(\"Down\"), this);\n connect(pAction, SIGNAL(triggered()), this, SLOT(down()));\n _menu.addAction(pAction);\n\n _menu.addSeparator();\n\n pAction = new QAction(tr(\"Delete\"), this);\n connect(pAction, SIGNAL(triggered()), this, SLOT(slotDelete()));\n _menu.addAction(pAction);\n}\n\nvoid\nParameterXML::slotSetParameters()\n{\n setParameters();\n}\n\nvoid\nParameterXML::setParameters()\n{\n}\nMake the QMenu the parent of the QAction\/\/ -*- c++ -*- \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ This file is part of Miro (The Middleware for Robots)\n\/\/ Copyright (C) 1999-2013\n\/\/ Department of Neural Information Processing, University of Ulm\n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Lesser General Public License as published\n\/\/ by the Free Software Foundation; either version 2, or (at your option)\n\/\/ any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public License\n\/\/ along with this program; if not, write to the Free Software Foundation,\n\/\/ Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n\/\/\n\n\/\/ This module\n#include \"ParameterXML.h\"\n\/\/ This application\n#include \"ConfigFile.h\"\n\/\/ The Qt library\n#include \n#include \n#include \n\/\/ The C++ Standard Library\n#include \n\nQString const ParameterXML::XML_TAG = \"parameter\";\n\nParameterXML::ParameterXML(QDomNode const& _node,\n\t\t\t QTreeWidgetItem * _parentItem,\n\t\t\t QTreeWidgetItem * _pre,\n\t\t\t QObject * _parent,\n\t\t\t const char * _name) :\n Super(_node, _parentItem, _pre, _parent, _name),\n config_(ConfigFile::instance())\n{\n assert(!node().toElement().isNull());\n}\n\nParameterXML::ParameterXML(QDomNode const& _node,\n\t\t\t QTreeWidget * _view,\n\t\t\t QTreeWidgetItem * _pre,\n\t\t\t QObject * _parent,\n\t\t\t const char * _name) :\n Super(_node, _view, _pre, _parent, _name),\n config_(ConfigFile::instance())\n{\n assert(!node().toElement().isNull());\n}\n\nvoid \nParameterXML::init()\n{\n}\n\nvoid\nParameterXML::contextMenu(QMenu& _menu)\n{\n \/\/ Add 4 QActions to the context menu: \"Set Parameters\", \"Up\", \"Down\" and\n \/\/ \"Delete\"\n QAction * pAction = NULL;\n\n pAction = new QAction(tr(\"Set Parameters\"), &_menu);\n connect(pAction, SIGNAL(triggered()), this, SLOT(slotSetParameters()));\n _menu.addAction(pAction);\n\n _menu.addSeparator();\n\n pAction = new QAction(tr(\"Up\"), &_menu);\n connect(pAction, SIGNAL(triggered()), this, SLOT(up()));\n _menu.addAction(pAction);\n\n pAction = new QAction(tr(\"Down\"), &_menu);\n connect(pAction, SIGNAL(triggered()), this, SLOT(down()));\n _menu.addAction(pAction);\n\n _menu.addSeparator();\n\n pAction = new QAction(tr(\"Delete\"), &_menu);\n connect(pAction, SIGNAL(triggered()), this, SLOT(slotDelete()));\n _menu.addAction(pAction);\n}\n\nvoid\nParameterXML::slotSetParameters()\n{\n setParameters();\n}\n\nvoid\nParameterXML::setParameters()\n{\n}\n<|endoftext|>"} {"text":"#include \"terminal.h\"\n\n#include \"filefinder.h\"\n#include \"options.h\"\n\nterminal::terminal(){\n \/\/ save and copy terminal settings\n tcgetattr( STDIN_FILENO, &oldt);\n newt = oldt;\n\n \/\/ set new terminal settings\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr( STDIN_FILENO, TCSANOW, &newt);\n\n \/\/\n for(int i=0; i < options.number_of_result_lines; ++i){\n fprintf(stderr,\"\\n\");\n }\n cursor_up(options.number_of_result_lines);\n save_cursor_pos();\n restore_cursor_pos();\n}\n\nterminal::~terminal(){\n \/\/ restore terminal settings\n tcsetattr( STDIN_FILENO, TCSANOW, &oldt);\n}\n\nvoid terminal::save_cursor_pos() const{\n fprintf(stderr,\"\\033[s\");\n}\n\nvoid terminal::restore_cursor_pos() const{\n fprintf(stderr,\"\\033[u\");\n}\n\nvoid terminal::erase_line() const{\n fprintf(stderr,\"\\033[K\");\n}\n\nvoid terminal::cursor_left(int n) const{\n fprintf(stderr,\"\\033[%dD\",n);\n}\n\nvoid terminal::cursor_right(int n) const{\n fprintf(stderr,\"\\033[%dC\",n);\n}\n\nvoid terminal::cursor_up(int n) const{\n fprintf(stderr,\"\\033[%dA\",n);\n}\n\nvoid terminal::cursor_down(int n) const{\n fprintf(stderr,\"\\033[%dB\",n);\n}\n\nvoid terminal::print_search_line(std::string str, int pos) const{\n restore_cursor_pos();\n erase_line();\n fprintf(stderr,\">%s\", str.c_str());\n restore_cursor_pos();\n cursor_right(1+pos);\n}\n\n\nvoid terminal::print_result(const terminal& term,const std::vector& result, std::size_t selected) const{\n term.restore_cursor_pos();\n for(int i=0; i < options.number_of_result_lines; ++i){\n fprintf(stderr,\"\\n\");\n term.erase_line();\n }\n term.restore_cursor_pos();\n\n for(std::size_t i=1; i <= result.size(); ++i){\n fprintf(stderr,\"\\n\");\n if(i-1==selected) fprintf(stderr,\"\\033[7m\");\n fprintf(stderr,\"%lu: %s%s\",(unsigned long)i,result[i-1].location.c_str(), result[i-1].filename.c_str());\n if(i-1==selected) fprintf(stderr,\"\\033[0m\");\n }\n}\nUpdate terminal.cpp#include \"terminal.h\"\n\n#include \"filefinder.h\"\n#include \"options.h\"\n\nterminal::terminal(){\n \/\/ save and copy terminal settings\n tcgetattr( STDIN_FILENO, &oldt);\n newt = oldt;\n\n \/\/ set new terminal settings\n newt.c_lflag &= ~(ICANON | ECHO);\n tcsetattr( STDIN_FILENO, TCSANOW, &newt);\n\n \/\/ print as many newlines as number_of_result_lines to\n \/\/ enable moving the cursor up and down.\n for(int i=0; i < options.number_of_result_lines; ++i){\n fprintf(stderr,\"\\n\");\n }\n cursor_up(options.number_of_result_lines);\n save_cursor_pos();\n restore_cursor_pos();\n}\n\nterminal::~terminal(){\n \/\/ restore terminal settings\n tcsetattr( STDIN_FILENO, TCSANOW, &oldt);\n}\n\nvoid terminal::save_cursor_pos() const{\n fprintf(stderr,\"\\033[s\");\n}\n\nvoid terminal::restore_cursor_pos() const{\n fprintf(stderr,\"\\033[u\");\n}\n\nvoid terminal::erase_line() const{\n fprintf(stderr,\"\\033[K\");\n}\n\nvoid terminal::cursor_left(int n) const{\n fprintf(stderr,\"\\033[%dD\",n);\n}\n\nvoid terminal::cursor_right(int n) const{\n fprintf(stderr,\"\\033[%dC\",n);\n}\n\nvoid terminal::cursor_up(int n) const{\n fprintf(stderr,\"\\033[%dA\",n);\n}\n\nvoid terminal::cursor_down(int n) const{\n fprintf(stderr,\"\\033[%dB\",n);\n}\n\nvoid terminal::print_search_line(std::string str, int pos) const{\n restore_cursor_pos();\n erase_line();\n fprintf(stderr,\">%s\", str.c_str());\n restore_cursor_pos();\n cursor_right(1+pos);\n}\n\n\nvoid terminal::print_result(const terminal& term,const std::vector& result, std::size_t selected) const{\n term.restore_cursor_pos();\n for(int i=0; i < options.number_of_result_lines; ++i){\n fprintf(stderr,\"\\n\");\n term.erase_line();\n }\n term.restore_cursor_pos();\n\n for(std::size_t i=1; i <= result.size(); ++i){\n fprintf(stderr,\"\\n\");\n if(i-1==selected) fprintf(stderr,\"\\033[7m\");\n fprintf(stderr,\"%lu: %s%s\",(unsigned long)i,result[i-1].location.c_str(), result[i-1].filename.c_str());\n if(i-1==selected) fprintf(stderr,\"\\033[0m\");\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \"textures.h\"\n#include \"util.h\"\n#define KONSTRUCTS_PATH_SIZE 256\n\nnamespace konstructs {\n void shtxt_path(const char *name, const char *type, char *path, size_t max_len) {\n snprintf(path, max_len, \"%s\/%s\", type, name);\n\n if (!file_exist(path)) {\n snprintf(path, max_len, \"..\/%s\/%s\", type, name);\n }\n\n if (!file_exist(path)) {\n snprintf(path, max_len, \"\/usr\/local\/share\/konstructs-client\/%s\/%s\", type, name);\n }\n\n if (!file_exist(path)) {\n printf(\"Error, no %s for %s found.\\n\", type, name);\n exit(1);\n }\n }\n\n void texture_path(const char *name, char *path, size_t max_len) {\n shtxt_path(name, \"textures\", path, max_len);\n }\n\n\n void load_textures() {\n char txtpth[KONSTRUCTS_PATH_SIZE];\n\n GLuint sky;\n glGenTextures(1, &sky);\n glActiveTexture(GL_TEXTURE0 + SKY_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, sky);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n texture_path(\"sky.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n\n GLuint font;\n glGenTextures(1, &font);\n glActiveTexture(GL_TEXTURE0 + FONT_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, font);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n texture_path(\"font.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n\n GLuint inventory_texture;\n glGenTextures(1, &inventory_texture);\n glActiveTexture(GL_TEXTURE0 + INVENTORY_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, inventory_texture);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n texture_path(\"inventory.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n }\n};\nUse GL_LINEAR instead of GL_NEAREST for better txt.#include \n#include \"textures.h\"\n#include \"util.h\"\n#define KONSTRUCTS_PATH_SIZE 256\n\nnamespace konstructs {\n void shtxt_path(const char *name, const char *type, char *path, size_t max_len) {\n snprintf(path, max_len, \"%s\/%s\", type, name);\n\n if (!file_exist(path)) {\n snprintf(path, max_len, \"..\/%s\/%s\", type, name);\n }\n\n if (!file_exist(path)) {\n snprintf(path, max_len, \"\/usr\/local\/share\/konstructs-client\/%s\/%s\", type, name);\n }\n\n if (!file_exist(path)) {\n printf(\"Error, no %s for %s found.\\n\", type, name);\n exit(1);\n }\n }\n\n void texture_path(const char *name, char *path, size_t max_len) {\n shtxt_path(name, \"textures\", path, max_len);\n }\n\n\n void load_textures() {\n char txtpth[KONSTRUCTS_PATH_SIZE];\n\n GLuint sky;\n glGenTextures(1, &sky);\n glActiveTexture(GL_TEXTURE0 + SKY_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, sky);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);\n texture_path(\"sky.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n\n GLuint font;\n glGenTextures(1, &font);\n glActiveTexture(GL_TEXTURE0 + FONT_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, font);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n texture_path(\"font.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n\n GLuint inventory_texture;\n glGenTextures(1, &inventory_texture);\n glActiveTexture(GL_TEXTURE0 + INVENTORY_TEXTURE);\n glBindTexture(GL_TEXTURE_2D, inventory_texture);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);\n texture_path(\"inventory.png\", txtpth, KONSTRUCTS_PATH_SIZE);\n load_png_texture(txtpth);\n }\n};\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nstatic Mutex g_timeoffset_mutex;\nstatic int64_t nTimeOffset GUARDED_BY(g_timeoffset_mutex) = 0;\n\n\/**\n * \"Never go to sea with two chronometers; take one or three.\"\n * Our three time sources are:\n * - System clock\n * - Median of other nodes clocks\n * - The user (asking the user to fix the system clock if the first two disagree)\n *\/\nint64_t GetTimeOffset()\n{\n LOCK(g_timeoffset_mutex);\n return nTimeOffset;\n}\n\nint64_t GetAdjustedTime()\n{\n return GetTime() + GetTimeOffset();\n}\n\nstatic int64_t abs64(int64_t n)\n{\n return (n >= 0 ? n : -n);\n}\n\n#define BITCOIN_TIMEDATA_MAX_SAMPLES 200\n\nvoid AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)\n{\n LOCK(g_timeoffset_mutex);\n \/\/ Ignore duplicates\n static std::set setKnown;\n if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)\n return;\n if (!setKnown.insert(ip).second)\n return;\n\n \/\/ Add data\n static CMedianFilter vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);\n vTimeOffsets.input(nOffsetSample);\n LogPrint(BCLog::NET,\"added time data, samples %d, offset %+d (%+d minutes)\\n\", vTimeOffsets.size(), nOffsetSample, nOffsetSample\/60);\n\n \/\/ There is a known issue here (see issue #4521):\n \/\/\n \/\/ - The structure vTimeOffsets contains up to 200 elements, after which\n \/\/ any new element added to it will not increase its size, replacing the\n \/\/ oldest element.\n \/\/\n \/\/ - The condition to update nTimeOffset includes checking whether the\n \/\/ number of elements in vTimeOffsets is odd, which will never happen after\n \/\/ there are 200 elements.\n \/\/\n \/\/ But in this case the 'bug' is protective against some attacks, and may\n \/\/ actually explain why we've never seen attacks which manipulate the\n \/\/ clock offset.\n \/\/\n \/\/ So we should hold off on fixing this and clean it up as part of\n \/\/ a timing cleanup that strengthens it in a number of other ways.\n \/\/\n if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)\n {\n int64_t nMedian = vTimeOffsets.median();\n std::vector vSorted = vTimeOffsets.sorted();\n \/\/ Only let other nodes change our time by so much\n if (abs64(nMedian) <= std::max(0, gArgs.GetArg(\"-maxtimeadjustment\", DEFAULT_MAX_TIME_ADJUSTMENT)))\n {\n nTimeOffset = nMedian;\n }\n else\n {\n nTimeOffset = 0;\n\n static bool fDone;\n if (!fDone)\n {\n \/\/ If nobody has a time different than ours but within 5 minutes of ours, give a warning\n bool fMatch = false;\n for (const int64_t nOffset : vSorted)\n if (nOffset != 0 && abs64(nOffset) < 5 * 60)\n fMatch = true;\n\n if (!fMatch)\n {\n fDone = true;\n bilingual_str strMessage = strprintf(_(\"Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.\"), PACKAGE_NAME);\n SetMiscWarning(strMessage.translated);\n uiInterface.ThreadSafeMessageBox(strMessage, \"\", CClientUIInterface::MSG_WARNING);\n }\n }\n }\n\n if (LogAcceptCategory(BCLog::NET)) {\n for (const int64_t n : vSorted) {\n LogPrint(BCLog::NET, \"%+d \", n); \/* Continued *\/\n }\n LogPrint(BCLog::NET, \"| \"); \/* Continued *\/\n\n LogPrint(BCLog::NET, \"nTimeOffset = %+d (%+d minutes)\\n\", nTimeOffset, nTimeOffset\/60);\n }\n }\n}\nrefactor: Fix formatting of timedata.cpp\/\/ Copyright (c) 2014-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic Mutex g_timeoffset_mutex;\nstatic int64_t nTimeOffset GUARDED_BY(g_timeoffset_mutex) = 0;\n\n\/**\n * \"Never go to sea with two chronometers; take one or three.\"\n * Our three time sources are:\n * - System clock\n * - Median of other nodes clocks\n * - The user (asking the user to fix the system clock if the first two disagree)\n *\/\nint64_t GetTimeOffset()\n{\n LOCK(g_timeoffset_mutex);\n return nTimeOffset;\n}\n\nint64_t GetAdjustedTime()\n{\n return GetTime() + GetTimeOffset();\n}\n\nstatic int64_t abs64(int64_t n)\n{\n return (n >= 0 ? n : -n);\n}\n\n#define BITCOIN_TIMEDATA_MAX_SAMPLES 200\n\nvoid AddTimeData(const CNetAddr& ip, int64_t nOffsetSample)\n{\n LOCK(g_timeoffset_mutex);\n \/\/ Ignore duplicates\n static std::set setKnown;\n if (setKnown.size() == BITCOIN_TIMEDATA_MAX_SAMPLES)\n return;\n if (!setKnown.insert(ip).second)\n return;\n\n \/\/ Add data\n static CMedianFilter vTimeOffsets(BITCOIN_TIMEDATA_MAX_SAMPLES, 0);\n vTimeOffsets.input(nOffsetSample);\n LogPrint(BCLog::NET, \"added time data, samples %d, offset %+d (%+d minutes)\\n\", vTimeOffsets.size(), nOffsetSample, nOffsetSample \/ 60);\n\n \/\/ There is a known issue here (see issue #4521):\n \/\/\n \/\/ - The structure vTimeOffsets contains up to 200 elements, after which\n \/\/ any new element added to it will not increase its size, replacing the\n \/\/ oldest element.\n \/\/\n \/\/ - The condition to update nTimeOffset includes checking whether the\n \/\/ number of elements in vTimeOffsets is odd, which will never happen after\n \/\/ there are 200 elements.\n \/\/\n \/\/ But in this case the 'bug' is protective against some attacks, and may\n \/\/ actually explain why we've never seen attacks which manipulate the\n \/\/ clock offset.\n \/\/\n \/\/ So we should hold off on fixing this and clean it up as part of\n \/\/ a timing cleanup that strengthens it in a number of other ways.\n \/\/\n if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1) {\n int64_t nMedian = vTimeOffsets.median();\n std::vector vSorted = vTimeOffsets.sorted();\n \/\/ Only let other nodes change our time by so much\n if (abs64(nMedian) <= std::max(0, gArgs.GetArg(\"-maxtimeadjustment\", DEFAULT_MAX_TIME_ADJUSTMENT))) {\n nTimeOffset = nMedian;\n } else {\n nTimeOffset = 0;\n\n static bool fDone;\n if (!fDone) {\n \/\/ If nobody has a time different than ours but within 5 minutes of ours, give a warning\n bool fMatch = false;\n for (const int64_t nOffset : vSorted) {\n if (nOffset != 0 && abs64(nOffset) < 5 * 60) fMatch = true;\n }\n\n if (!fMatch) {\n fDone = true;\n bilingual_str strMessage = strprintf(_(\"Please check that your computer's date and time are correct! If your clock is wrong, %s will not work properly.\"), PACKAGE_NAME);\n SetMiscWarning(strMessage.translated);\n uiInterface.ThreadSafeMessageBox(strMessage, \"\", CClientUIInterface::MSG_WARNING);\n }\n }\n }\n\n if (LogAcceptCategory(BCLog::NET)) {\n for (const int64_t n : vSorted) {\n LogPrint(BCLog::NET, \"%+d \", n); \/* Continued *\/\n }\n LogPrint(BCLog::NET, \"| \"); \/* Continued *\/\n LogPrint(BCLog::NET, \"nTimeOffset = %+d (%+d minutes)\\n\", nTimeOffset, nTimeOffset \/ 60);\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \"tokenizer.h\"\n#include \"shl_exception.h\"\n\nusing std::stack;\nusing std::function;\nusing std::unordered_set;\nusing std::set;\n\nnamespace shl {\n\nvector > Tokenizer::tokenize(const Grammar& grammar, const string& text) {\n vector > tokens;\n vector pattern_stack;\n\n tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name)));\n tokenize(text, grammar, Match::make_dummy(0,0), pattern_stack, tokens);\n\n return tokens;\n}\n\nvoid for_all_subrules(const Pattern& rule, set& visited, function callback) {\n const Pattern& real_rule = (rule.include)? *rule.include : rule;\n if (visited.count(&real_rule) > 0) return;\n visited.insert(&real_rule);\n\n if (real_rule.begin.empty()) {\n for (auto& subrule : real_rule.patterns) {\n for_all_subrules(subrule, visited, callback);\n }\n } else {\n callback(real_rule);\n }\n}\n\nvoid for_all_subrules(const vector& patterns, function callback) {\n set visited;\n for (auto& rule : patterns) {\n for_all_subrules(rule, visited, callback);\n }\n}\n\ninline bool is_end_match_first(const Pattern& pattern, const Match& end_match, const Match& current_first_match) {\n if (pattern.applyEndPatternLast) {\n return end_match[0].position < current_first_match[0].position;\n } else {\n return end_match[0].position <= current_first_match[0].position;\n }\n}\n\n\/**\n * Find the next lexeme iteratively\n *\n * This method find the next lexeme by matching all begin field of the sub-patterns\n * of current rule, and its own end field, whichever comes first will be seleteced\n *\n * When true returned, found will contain the selected next pattern, and match will hold \n * the results. When false returned, there are 3 scenarios:\n * 1. end field is matched, found & match contains results\n * 2. current pattern is toplevel rule, so no end field, found is nullptr\n * 3. When nothing can be matched(either source text or syntax definition is invalid),\n * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception\n * will be thrown\n *\n * Note:\n * begin_end_pos: this is the offset of current pattern's begin match.end(), it's meant to \n * support Perl style \\G, and stands for the *previous* match.end()\n *\/\nbool Tokenizer::next_lexeme(const string& text, const int begin_end_pos, const Match& begin_lexeme, const Pattern& pattern, const Pattern** found, Match& match) {\n int pos = begin_lexeme[0].end();\n const Pattern* found_pattern = nullptr;\n Match first_match;\n bool is_close = false;\n\n \/\/ first find pattern or end pattern, whichever comes first\n for_all_subrules(pattern.patterns, [&found_pattern, &first_match, pos, &text, begin_end_pos](const Pattern& sub_pattern) {\n Match tmp = sub_pattern.begin.match(text, pos, begin_end_pos);\n if (tmp != Match::NOT_MATCHED) {\n if( found_pattern == nullptr || tmp[0].position < first_match[0].position) {\n first_match = std::move(tmp); \n found_pattern = &sub_pattern;\n }\n }\n });\n if (!pattern.end.empty()) {\n Match end_match = pattern.end.match(text, pos, begin_end_pos);\n if (end_match != Match::NOT_MATCHED) {\n if( found_pattern == nullptr || is_end_match_first(pattern, end_match, first_match)) {\n first_match = std::move(end_match); \n found_pattern = &pattern;\n is_close = true;\n }\n }\n }\n if ( found_pattern != nullptr) {\n *found = found_pattern;\n match = first_match;\n return !is_close;\n }\n\n \/\/ special handle for toplevel rule\n if (pattern.end.empty()) {\n \/\/ all rule with begin will has an end, which is enforced by grammar loader\n \/\/ so only toplevel rules can be here\n *found = nullptr;\n is_close = true;\n return false;\n }\n\n \/\/ When no lexeme found\n if (_option & OPTION_TOLERATE_ERROR) {\n *found = nullptr;\n return false;\n } else {\n throw InvalidSourceException(\"scope not properly closed\"); \n }\n}\n\nvector get_name(vector& stack, const string& name, const string& enclosing_name) {\n vector names;\n\n for(auto pattern : stack) {\n names.push_back(pattern->name);\n names.push_back(pattern->content_name);\n }\n if (!enclosing_name.empty()) names.push_back(enclosing_name);\n names.push_back(name); \/\/ name can't be empty\n\n return names;\n}\n\nvoid Tokenizer::add_scope(vector >& tokens, const Range& range, vector& stack, const string& name, const string& enclosing_name = \"\") {\n if (name.empty()) return;\n if (range.length == 0) return; \/\/ only captures can potentially has 0 length\n\n Scope scope(get_name(stack, name, enclosing_name));\n tokens.push_back(std::make_pair(range, scope));\n}\n\ninline void append_back(vector >& target, const vector >& source ) {\n std::move(source.begin(), source.end(), std::back_inserter(target));\n}\n\nvoid Tokenizer::process_capture(vector >& tokens, const Match& match, vector& stack, const map& capture, const string& enclosing_name) {\n for (auto& pair : capture) {\n unsigned int capture_num = pair.first;\n const string& name = pair.second;\n if (match.size() > capture_num) {\n add_scope(tokens, match[capture_num], stack, name, enclosing_name);\n } else {\n if (_option & OPTION_STRICT) {\n throw InvalidSourceException(\"capture number out of range\");\n }\n }\n }\n}\n\nMatch Tokenizer::tokenize(const string& text, const Pattern& pattern, const Match& begin_lexeme, vector& stack, vector >& tokens) {\n stack.push_back(&pattern);\n\n int begin_end_pos = begin_lexeme[0].end();\n const Pattern* found_pattern = nullptr;\n Match last_lexeme, match;\n last_lexeme = begin_lexeme;\n while(next_lexeme(text, begin_end_pos, last_lexeme, pattern, &found_pattern, match)) {\n if (found_pattern->is_match_rule) {\n add_scope(tokens, match[0], stack, found_pattern->name);\n process_capture(tokens, match, stack, found_pattern->captures, found_pattern->name);\n last_lexeme = match;\n\n } else {\n vector > child_tokens;\n\n Match end_match = tokenize(text, *found_pattern, match, stack, child_tokens);\n \n Range name_range = Range(match[0].position, end_match[0].end() - match[0].position);\n add_scope(tokens, name_range, stack, found_pattern->name);\n process_capture(tokens, match, stack, found_pattern->begin_captures, found_pattern->name);\n\n Range content_range = Range(match[0].end(), end_match[0].position - match[0].end());\n add_scope(tokens, content_range, stack, found_pattern->content_name, found_pattern->name);\n \n append_back(tokens, child_tokens);\n process_capture(tokens, end_match, stack, found_pattern->end_captures, found_pattern->name);\n last_lexeme = end_match;\n }\n }\n\n stack.pop_back();\n\n if ( found_pattern == nullptr) { \/\/see comments for next_lexeme\n return last_lexeme; \n } else {\n return match; \n }\n\n}\n\n}\nadd comment#include \n#include \n#include \n#include \n#include \n#include \n#include \"tokenizer.h\"\n#include \"shl_exception.h\"\n\nusing std::stack;\nusing std::function;\nusing std::unordered_set;\nusing std::set;\n\nnamespace shl {\n\nvector > Tokenizer::tokenize(const Grammar& grammar, const string& text) {\n vector > tokens;\n vector pattern_stack;\n\n tokens.push_back(std::make_pair(Range(0, text.size()), Scope(grammar.name)));\n tokenize(text, grammar, Match::make_dummy(0,0), pattern_stack, tokens);\n\n return tokens;\n}\n\nvoid for_all_subrules(const Pattern& rule, set& visited, function callback) {\n const Pattern& real_rule = (rule.include)? *rule.include : rule;\n if (visited.count(&real_rule) > 0) return;\n visited.insert(&real_rule);\n\n if (real_rule.begin.empty()) {\n for (auto& subrule : real_rule.patterns) {\n for_all_subrules(subrule, visited, callback);\n }\n } else {\n \/\/ we don't need to look at it's subrule at this time\n callback(real_rule);\n }\n}\n\nvoid for_all_subrules(const vector& patterns, function callback) {\n set visited;\n for (auto& rule : patterns) {\n for_all_subrules(rule, visited, callback);\n }\n}\n\ninline bool is_end_match_first(const Pattern& pattern, const Match& end_match, const Match& current_first_match) {\n if (pattern.applyEndPatternLast) {\n return end_match[0].position < current_first_match[0].position;\n } else {\n return end_match[0].position <= current_first_match[0].position;\n }\n}\n\n\/**\n * Find the next lexeme iteratively\n *\n * This method find the next lexeme by matching all begin field of the sub-patterns\n * of current rule, and its own end field, whichever comes first will be seleteced\n *\n * When true returned, found will contain the selected next pattern, and match will hold \n * the results. When false returned, there are 3 scenarios:\n * 1. end field is matched, found & match contains results\n * 2. current pattern is toplevel rule, so no end field, found is nullptr\n * 3. When nothing can be matched(either source text or syntax definition is invalid),\n * and user specified OPTION_TOLERATE_ERROR, found will be nullptr, otherwise exception\n * will be thrown\n *\n * Note:\n * begin_end_pos: this is the offset of current pattern's begin match.end(), it's meant to \n * support Perl style \\G, and stands for the *previous* match.end()\n *\/\nbool Tokenizer::next_lexeme(const string& text, const int begin_end_pos, const Match& begin_lexeme, const Pattern& pattern, const Pattern** found, Match& match) {\n int pos = begin_lexeme[0].end();\n const Pattern* found_pattern = nullptr;\n Match first_match;\n bool is_close = false;\n\n \/\/ first find pattern or end pattern, whichever comes first\n for_all_subrules(pattern.patterns, [&found_pattern, &first_match, pos, &text, begin_end_pos](const Pattern& sub_pattern) {\n Match tmp = sub_pattern.begin.match(text, pos, begin_end_pos);\n if (tmp != Match::NOT_MATCHED) {\n if( found_pattern == nullptr || tmp[0].position < first_match[0].position) {\n first_match = std::move(tmp); \n found_pattern = &sub_pattern;\n }\n }\n });\n if (!pattern.end.empty()) {\n Match end_match = pattern.end.match(text, pos, begin_end_pos);\n if (end_match != Match::NOT_MATCHED) {\n if( found_pattern == nullptr || is_end_match_first(pattern, end_match, first_match)) {\n first_match = std::move(end_match); \n found_pattern = &pattern;\n is_close = true;\n }\n }\n }\n if ( found_pattern != nullptr) {\n *found = found_pattern;\n match = first_match;\n return !is_close;\n }\n\n \/\/ special handle for toplevel rule\n if (pattern.end.empty()) {\n \/\/ all rule with begin will has an end, which is enforced by grammar loader\n \/\/ so only toplevel rules can be here\n *found = nullptr;\n is_close = true;\n return false;\n }\n\n \/\/ When no lexeme found\n if (_option & OPTION_TOLERATE_ERROR) {\n *found = nullptr;\n return false;\n } else {\n throw InvalidSourceException(\"scope not properly closed\"); \n }\n}\n\nvector get_name(vector& stack, const string& name, const string& enclosing_name) {\n vector names;\n\n for(auto pattern : stack) {\n names.push_back(pattern->name);\n names.push_back(pattern->content_name);\n }\n if (!enclosing_name.empty()) names.push_back(enclosing_name);\n names.push_back(name); \/\/ name can't be empty\n\n return names;\n}\n\nvoid Tokenizer::add_scope(vector >& tokens, const Range& range, vector& stack, const string& name, const string& enclosing_name = \"\") {\n if (name.empty()) return;\n if (range.length == 0) return; \/\/ only captures can potentially has 0 length\n\n Scope scope(get_name(stack, name, enclosing_name));\n tokens.push_back(std::make_pair(range, scope));\n}\n\ninline void append_back(vector >& target, const vector >& source ) {\n std::move(source.begin(), source.end(), std::back_inserter(target));\n}\n\nvoid Tokenizer::process_capture(vector >& tokens, const Match& match, vector& stack, const map& capture, const string& enclosing_name) {\n for (auto& pair : capture) {\n unsigned int capture_num = pair.first;\n const string& name = pair.second;\n if (match.size() > capture_num) {\n add_scope(tokens, match[capture_num], stack, name, enclosing_name);\n } else {\n if (_option & OPTION_STRICT) {\n throw InvalidSourceException(\"capture number out of range\");\n }\n }\n }\n}\n\nMatch Tokenizer::tokenize(const string& text, const Pattern& pattern, const Match& begin_lexeme, vector& stack, vector >& tokens) {\n stack.push_back(&pattern);\n\n int begin_end_pos = begin_lexeme[0].end();\n const Pattern* found_pattern = nullptr;\n Match last_lexeme, match;\n last_lexeme = begin_lexeme;\n while(next_lexeme(text, begin_end_pos, last_lexeme, pattern, &found_pattern, match)) {\n if (found_pattern->is_match_rule) {\n add_scope(tokens, match[0], stack, found_pattern->name);\n process_capture(tokens, match, stack, found_pattern->captures, found_pattern->name);\n last_lexeme = match;\n\n } else {\n vector > child_tokens;\n\n Match end_match = tokenize(text, *found_pattern, match, stack, child_tokens);\n \n Range name_range = Range(match[0].position, end_match[0].end() - match[0].position);\n add_scope(tokens, name_range, stack, found_pattern->name);\n process_capture(tokens, match, stack, found_pattern->begin_captures, found_pattern->name);\n\n Range content_range = Range(match[0].end(), end_match[0].position - match[0].end());\n add_scope(tokens, content_range, stack, found_pattern->content_name, found_pattern->name);\n \n append_back(tokens, child_tokens);\n process_capture(tokens, end_match, stack, found_pattern->end_captures, found_pattern->name);\n last_lexeme = end_match;\n }\n }\n\n stack.pop_back();\n\n if ( found_pattern == nullptr) { \/\/see comments for next_lexeme\n return last_lexeme; \n } else {\n return match; \n }\n\n}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#define VK_Z_KEY 0x5A\n\/\/ These keys are used to send windows to tray\n#define TRAY_KEY VK_Z_KEY\n#define MOD_KEY MOD_WIN + MOD_SHIFT\n\n#define WM_ICON 0x1C0A\n#define WM_OURICON 0x1C0B\n#define EXIT_ID 0x99\n#define SHOW_ALL_ID 0x98\n#define MAXIMUM_WINDOWS 100\n\n\/\/ Stores hidden window record.\ntypedef struct HIDDEN_WINDOW {\n NOTIFYICONDATA icon;\n HWND window;\n} HIDDEN_WINDOW;\n\n\/\/ Current execution context\ntypedef struct TRCONTEXT {\n HWND mainWindow;\n HIDDEN_WINDOW icons[MAXIMUM_WINDOWS];\n HMENU trayMenu;\n int iconIndex; \/\/ How many windows are currently hidden\n} TRCONTEXT;\n\nHANDLE saveFile;\n\n\/\/ Saves our hidden windows so they can be restored in case\n\/\/ of crashing.\nvoid save(const TRCONTEXT *context) {\n DWORD numbytes;\n \/\/ Truncate file\n SetFilePointer(saveFile, 0, NULL, FILE_BEGIN);\n SetEndOfFile(saveFile);\n if (!context->iconIndex) {\n return;\n }\n for (int i = 0; i < context->iconIndex; i++)\n {\n if (context->icons[i].window) {\n std::string str;\n str = std::to_string((long)context->icons[i].window);\n str += ',';\n const char *handleString = str.c_str();\n WriteFile(saveFile, handleString, strlen(handleString), &numbytes, NULL);\n }\n\n }\n\n}\n\n\/\/ Restores a window\nvoid showWindow(TRCONTEXT *context, LPARAM lParam) {\n for (int i = 0; i < context->iconIndex; i++)\n {\n if (context->icons[i].icon.uID == HIWORD(lParam)) {\n ShowWindow(context->icons[i].window, SW_SHOW);\n Shell_NotifyIcon(NIM_DELETE, &context->icons[i].icon);\n SetForegroundWindow(context->icons[i].window);\n context->icons[i] = {};\n std::vector temp = std::vector(context->iconIndex);\n \/\/ Restructure array so there are no holes\n for (int j = 0, x = 0; j < context->iconIndex; j++)\n {\n if (context->icons[j].window) {\n temp[x] = context->icons[j];\n x++;\n }\n }\n memcpy_s(context->icons, sizeof(context->icons), &temp.front(), sizeof(HIDDEN_WINDOW)*context->iconIndex);\n context->iconIndex--;\n save(context);\n break;\n }\n }\n}\n\n\/\/ Minimizes the current window to tray.\n\/\/ Uses currently focused window unless supplied a handle as the argument.\nvoid minimizeToTray(TRCONTEXT *context, long restoreWindow) {\n \/\/ Taskbar and desktop windows are restricted from hiding.\n const char restrictWins[][14] = { {\"WorkerW\"}, {\"Shell_TrayWnd\"} };\n\n HWND currWin = 0;\n if (!restoreWindow) {\n currWin = GetForegroundWindow();\n }\n else {\n currWin = reinterpret_cast(restoreWindow);\n }\n\n if (!currWin) {\n return;\n }\n\n char className[256];\n if (!GetClassName(currWin, className, 256)) {\n return;\n }\n else {\n for (int i = 0; i < sizeof(restrictWins) \/ sizeof(*restrictWins); i++)\n {\n if (strcmp(restrictWins[i], className) == 0) {\n return;\n }\n }\n }\n if (context->iconIndex == MAXIMUM_WINDOWS) {\n MessageBox(NULL, \"Error! Too many hidden windows. Please unhide some.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return;\n }\n ULONG_PTR icon = GetClassLongPtr(currWin, GCLP_HICONSM);\n if (!icon) {\n icon = SendMessage(currWin, WM_GETICON, 2, NULL);\n if (!icon) {\n return;\n }\n }\n\n NOTIFYICONDATA nid;\n nid.cbSize = sizeof(NOTIFYICONDATA);\n nid.hWnd = context->mainWindow;\n nid.hIcon = (HICON)icon;\n nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP;\n nid.uVersion = NOTIFYICON_VERSION_4;\n nid.uID = LOWORD(reinterpret_cast(currWin));\n nid.uCallbackMessage = WM_ICON;\n GetWindowText(currWin, nid.szTip, 128);\n for (int i = 0; i < context->iconIndex; i++) {\n if (context->icons[i].icon.uID == nid.uID) {\n return;\n }\n }\n context->icons[context->iconIndex].icon = nid;\n context->icons[context->iconIndex].window = currWin;\n context->iconIndex++;\n Shell_NotifyIcon(NIM_ADD, &nid);\n Shell_NotifyIcon(NIM_SETVERSION, &nid);\n ShowWindow(currWin, SW_HIDE);\n if (!restoreWindow) {\n save(context);\n }\n\n}\n\n\/\/ Adds our own icon to tray\nvoid createTrayIcon(HWND mainWindow, HINSTANCE hInstance, NOTIFYICONDATA* icon) {\n icon->cbSize = sizeof(NOTIFYICONDATA);\n icon->hWnd = mainWindow;\n icon->hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(101));\n icon->uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP | NIF_MESSAGE;\n icon->uVersion = NOTIFYICON_VERSION_4;\n icon->uID = reinterpret_cast(mainWindow);\n icon->uCallbackMessage = WM_OURICON;\n strcpy_s(icon->szTip, \"Traymond\");\n Shell_NotifyIcon(NIM_ADD, icon);\n Shell_NotifyIcon(NIM_SETVERSION, icon);\n}\n\n\/\/ Creates our tray icon menu\nvoid createTrayMenu(HMENU* trayMenu) {\n *trayMenu = CreatePopupMenu();\n\n MENUITEMINFO showAllMenuItem;\n MENUITEMINFO exitMenuItem;\n\n exitMenuItem.cbSize = sizeof(MENUITEMINFO);\n exitMenuItem.fMask = MIIM_STRING | MIIM_ID;\n exitMenuItem.fType = MFT_STRING;\n exitMenuItem.dwTypeData = \"Exit\";\n exitMenuItem.cch = 5;\n exitMenuItem.wID = EXIT_ID;\n\n showAllMenuItem.cbSize = sizeof(MENUITEMINFO);\n showAllMenuItem.fMask = MIIM_STRING | MIIM_ID;\n showAllMenuItem.fType = MFT_STRING;\n showAllMenuItem.dwTypeData = \"Restore all windows\";\n showAllMenuItem.cch = 20;\n showAllMenuItem.wID = SHOW_ALL_ID;\n\n InsertMenuItem(*trayMenu, 0, FALSE, &showAllMenuItem);\n InsertMenuItem(*trayMenu, 0, FALSE, &exitMenuItem);\n}\n\/\/ Shows all hidden windows;\nvoid showAllWindows(TRCONTEXT *context) {\n for (int i = 0; i < context->iconIndex; i++)\n {\n ShowWindow(context->icons[i].window, SW_SHOW);\n Shell_NotifyIcon(NIM_DELETE, &context->icons[i].icon);\n context->icons[i] = {};\n }\n save(context);\n context->iconIndex = 0;\n}\n\nvoid exitApp() {\n PostQuitMessage(0);\n}\n\n\/\/ Creates and reads the save file to restore hidden windows in case of unexpected termination\nvoid startup(TRCONTEXT *context) {\n if ((saveFile = CreateFile(\"traymond.dat\", GENERIC_READ | GENERIC_WRITE, \\\n 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {\n MessageBox(NULL, \"Error! Traymond could not create a save file.\", \"Traymond\", MB_OK | MB_ICONERROR);\n exitApp();\n }\n \/\/ Check if we've crashed (i. e. there is a save file) during current uptime and\n \/\/ if there are windows to restore, in which case restore them and\n \/\/ display a reassuring message.\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n DWORD numbytes;\n DWORD fileSize = GetFileSize(saveFile, NULL);\n\n if (!fileSize) {\n return;\n };\n\n FILETIME saveFileWriteTime;\n GetFileTime(saveFile, NULL, NULL, &saveFileWriteTime);\n uint64_t writeTime = ((uint64_t)saveFileWriteTime.dwHighDateTime << 32 | (uint64_t)saveFileWriteTime.dwLowDateTime) \/ 10000;\n GetSystemTimeAsFileTime(&saveFileWriteTime);\n writeTime = (((uint64_t)saveFileWriteTime.dwHighDateTime << 32 | (uint64_t)saveFileWriteTime.dwLowDateTime) \/ 10000) - writeTime;\n\n if (GetTickCount64() < writeTime) {\n return;\n }\n\n std::vector contents = std::vector(fileSize);\n ReadFile(saveFile, &contents.front(), fileSize, &numbytes, NULL);\n char handle[10];\n int index = 0;\n for (size_t i = 0; i < fileSize; i++)\n {\n if (contents[i] != ',') {\n handle[index] = contents[i];\n index++;\n }\n else {\n index = 0;\n minimizeToTray(context, std::stoi(std::string(handle)));\n memset(handle, 0, sizeof(handle));\n }\n }\n std::string restore_message = \"Traymond had previously been terminated unexpectedly.\\n\\nRestored \" + \\\n std::to_string(context->iconIndex) + (context->iconIndex > 1 ? \" icons.\" : \" icon.\");\n MessageBox(NULL, restore_message.c_str(), \"Traymond\", MB_OK);\n }\n }\n\nLRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n\n TRCONTEXT* context = reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA));\n POINT pt;\n switch (uMsg)\n {\n case WM_ICON:\n if (LOWORD(lParam) == WM_LBUTTONDBLCLK) {\n showWindow(context, lParam);\n }\n break;\n case WM_OURICON:\n if (LOWORD(lParam) == WM_RBUTTONUP) {\n SetForegroundWindow(hwnd);\n GetCursorPos(&pt);\n TrackPopupMenuEx(context->trayMenu, \\\n (GetSystemMetrics(SM_MENUDROPALIGNMENT) ? TPM_RIGHTALIGN : TPM_LEFTALIGN) | TPM_BOTTOMALIGN, \\\n pt.x, pt.y, hwnd, NULL);\n }\n break;\n case WM_COMMAND:\n if (HIWORD(wParam) == 0) {\n switch LOWORD(wParam) {\n case SHOW_ALL_ID:\n showAllWindows(context);\n break;\n case EXIT_ID:\n exitApp();\n break;\n }\n }\n break;\n case WM_HOTKEY: \/\/ We only have one hotkey, so no need to check the message\n minimizeToTray(context, NULL);\n break;\n default:\n return DefWindowProc(hwnd, uMsg, wParam, lParam);\n }\n return 0;\n}\n\n#pragma warning( push )\n#pragma warning( disable : 4100 )\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {\n#pragma warning( pop )\n\n TRCONTEXT context = {};\n\n NOTIFYICONDATA icon = {};\n\n \/\/ Mutex to allow only one instance\n const char szUniqueNamedMutex[] = \"traymond_mutex\";\n HANDLE mutex = CreateMutex(NULL, TRUE, szUniqueNamedMutex);\n if (GetLastError() == ERROR_ALREADY_EXISTS)\n {\n MessageBox(NULL, \"Error! Another instance of Traymond is already running.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return 1;\n }\n\n BOOL bRet;\n MSG msg;\n\n const char CLASS_NAME[] = \"Traymond\";\n\n WNDCLASS wc = {};\n wc.lpfnWndProc = WindowProc;\n wc.hInstance = hInstance;\n wc.lpszClassName = CLASS_NAME;\n\n if (!RegisterClass(&wc)) {\n return 1;\n }\n\n context.mainWindow = CreateWindow(CLASS_NAME, NULL, NULL, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);\n\n if (!context.mainWindow) {\n return 1;\n }\n\n \/\/ Store our context in main window for retrieval by WindowProc\n SetWindowLongPtr(context.mainWindow, GWLP_USERDATA, reinterpret_cast(&context));\n\n if (!RegisterHotKey(context.mainWindow, 0, MOD_KEY | MOD_NOREPEAT, TRAY_KEY)) {\n MessageBox(NULL, \"Error! Could not register the hotkey.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return 1;\n }\n\n createTrayIcon(context.mainWindow, hInstance, &icon);\n createTrayMenu(&context.trayMenu);\n startup(&context);\n\n while ((bRet = GetMessage(&msg, 0, 0, 0)) != 0)\n {\n if (bRet != -1) {\n DispatchMessage(&msg);\n }\n }\n \/\/ Clean up on exit;\n showAllWindows(&context);\n Shell_NotifyIcon(NIM_DELETE, &icon);\n ReleaseMutex(mutex);\n CloseHandle(mutex);\n CloseHandle(saveFile);\n DestroyMenu(context.trayMenu);\n DestroyWindow(context.mainWindow);\n DeleteFile(\"traymond.dat\"); \/\/ No save file means we have exited gracefully\n UnregisterHotKey(context.mainWindow, 0);\n return msg.wParam;\n}\nFix interaction with pinned applications#include \n#include \n#include \n#include \n\n#define VK_Z_KEY 0x5A\n\/\/ These keys are used to send windows to tray\n#define TRAY_KEY VK_Z_KEY\n#define MOD_KEY MOD_WIN + MOD_SHIFT\n\n#define WM_ICON 0x1C0A\n#define WM_OURICON 0x1C0B\n#define EXIT_ID 0x99\n#define SHOW_ALL_ID 0x98\n#define MAXIMUM_WINDOWS 100\n\n\/\/ Stores hidden window record.\ntypedef struct HIDDEN_WINDOW {\n NOTIFYICONDATA icon;\n HWND window;\n} HIDDEN_WINDOW;\n\n\/\/ Current execution context\ntypedef struct TRCONTEXT {\n HWND mainWindow;\n HIDDEN_WINDOW icons[MAXIMUM_WINDOWS];\n HMENU trayMenu;\n int iconIndex; \/\/ How many windows are currently hidden\n} TRCONTEXT;\n\nHANDLE saveFile;\n\n\/\/ Saves our hidden windows so they can be restored in case\n\/\/ of crashing.\nvoid save(const TRCONTEXT *context) {\n DWORD numbytes;\n \/\/ Truncate file\n SetFilePointer(saveFile, 0, NULL, FILE_BEGIN);\n SetEndOfFile(saveFile);\n if (!context->iconIndex) {\n return;\n }\n for (int i = 0; i < context->iconIndex; i++)\n {\n if (context->icons[i].window) {\n std::string str;\n str = std::to_string((long)context->icons[i].window);\n str += ',';\n const char *handleString = str.c_str();\n WriteFile(saveFile, handleString, strlen(handleString), &numbytes, NULL);\n }\n\n }\n\n}\n\n\/\/ Restores a window\nvoid showWindow(TRCONTEXT *context, LPARAM lParam) {\n for (int i = 0; i < context->iconIndex; i++)\n {\n if (context->icons[i].icon.uID == HIWORD(lParam)) {\n ShowWindow(context->icons[i].window, SW_SHOW);\n Shell_NotifyIcon(NIM_DELETE, &context->icons[i].icon);\n SetForegroundWindow(context->icons[i].window);\n context->icons[i] = {};\n std::vector temp = std::vector(context->iconIndex);\n \/\/ Restructure array so there are no holes\n for (int j = 0, x = 0; j < context->iconIndex; j++)\n {\n if (context->icons[j].window) {\n temp[x] = context->icons[j];\n x++;\n }\n }\n memcpy_s(context->icons, sizeof(context->icons), &temp.front(), sizeof(HIDDEN_WINDOW)*context->iconIndex);\n context->iconIndex--;\n save(context);\n break;\n }\n }\n}\n\n\/\/ Minimizes the current window to tray.\n\/\/ Uses currently focused window unless supplied a handle as the argument.\nvoid minimizeToTray(TRCONTEXT *context, long restoreWindow) {\n \/\/ Taskbar and desktop windows are restricted from hiding.\n const char restrictWins[][14] = { {\"WorkerW\"}, {\"Shell_TrayWnd\"} };\n\n HWND currWin = 0;\n if (!restoreWindow) {\n currWin = GetForegroundWindow();\n }\n else {\n currWin = reinterpret_cast(restoreWindow);\n }\n\n if (!currWin) {\n return;\n }\n\n char className[256];\n if (!GetClassName(currWin, className, 256)) {\n return;\n }\n else {\n for (int i = 0; i < sizeof(restrictWins) \/ sizeof(*restrictWins); i++)\n {\n if (strcmp(restrictWins[i], className) == 0) {\n return;\n }\n }\n }\n if (context->iconIndex == MAXIMUM_WINDOWS) {\n MessageBox(NULL, \"Error! Too many hidden windows. Please unhide some.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return;\n }\n ULONG_PTR icon = GetClassLongPtr(currWin, GCLP_HICONSM);\n if (!icon) {\n icon = SendMessage(currWin, WM_GETICON, 2, NULL);\n if (!icon) {\n return;\n }\n }\n\n NOTIFYICONDATA nid;\n nid.cbSize = sizeof(NOTIFYICONDATA);\n nid.hWnd = context->mainWindow;\n nid.hIcon = (HICON)icon;\n nid.uFlags = NIF_MESSAGE | NIF_ICON | NIF_TIP | NIF_SHOWTIP;\n nid.uVersion = NOTIFYICON_VERSION_4;\n nid.uID = LOWORD(reinterpret_cast(currWin));\n nid.uCallbackMessage = WM_ICON;\n GetWindowText(currWin, nid.szTip, 128);\n context->icons[context->iconIndex].icon = nid;\n context->icons[context->iconIndex].window = currWin;\n context->iconIndex++;\n Shell_NotifyIcon(NIM_ADD, &nid);\n Shell_NotifyIcon(NIM_SETVERSION, &nid);\n ShowWindow(currWin, SW_HIDE);\n if (!restoreWindow) {\n save(context);\n }\n\n}\n\n\/\/ Adds our own icon to tray\nvoid createTrayIcon(HWND mainWindow, HINSTANCE hInstance, NOTIFYICONDATA* icon) {\n icon->cbSize = sizeof(NOTIFYICONDATA);\n icon->hWnd = mainWindow;\n icon->hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(101));\n icon->uFlags = NIF_ICON | NIF_TIP | NIF_SHOWTIP | NIF_MESSAGE;\n icon->uVersion = NOTIFYICON_VERSION_4;\n icon->uID = reinterpret_cast(mainWindow);\n icon->uCallbackMessage = WM_OURICON;\n strcpy_s(icon->szTip, \"Traymond\");\n Shell_NotifyIcon(NIM_ADD, icon);\n Shell_NotifyIcon(NIM_SETVERSION, icon);\n}\n\n\/\/ Creates our tray icon menu\nvoid createTrayMenu(HMENU* trayMenu) {\n *trayMenu = CreatePopupMenu();\n\n MENUITEMINFO showAllMenuItem;\n MENUITEMINFO exitMenuItem;\n\n exitMenuItem.cbSize = sizeof(MENUITEMINFO);\n exitMenuItem.fMask = MIIM_STRING | MIIM_ID;\n exitMenuItem.fType = MFT_STRING;\n exitMenuItem.dwTypeData = \"Exit\";\n exitMenuItem.cch = 5;\n exitMenuItem.wID = EXIT_ID;\n\n showAllMenuItem.cbSize = sizeof(MENUITEMINFO);\n showAllMenuItem.fMask = MIIM_STRING | MIIM_ID;\n showAllMenuItem.fType = MFT_STRING;\n showAllMenuItem.dwTypeData = \"Restore all windows\";\n showAllMenuItem.cch = 20;\n showAllMenuItem.wID = SHOW_ALL_ID;\n\n InsertMenuItem(*trayMenu, 0, FALSE, &showAllMenuItem);\n InsertMenuItem(*trayMenu, 0, FALSE, &exitMenuItem);\n}\n\/\/ Shows all hidden windows;\nvoid showAllWindows(TRCONTEXT *context) {\n for (int i = 0; i < context->iconIndex; i++)\n {\n ShowWindow(context->icons[i].window, SW_SHOW);\n Shell_NotifyIcon(NIM_DELETE, &context->icons[i].icon);\n context->icons[i] = {};\n }\n save(context);\n context->iconIndex = 0;\n}\n\nvoid exitApp() {\n PostQuitMessage(0);\n}\n\n\/\/ Creates and reads the save file to restore hidden windows in case of unexpected termination\nvoid startup(TRCONTEXT *context) {\n if ((saveFile = CreateFile(\"traymond.dat\", GENERIC_READ | GENERIC_WRITE, \\\n 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) {\n MessageBox(NULL, \"Error! Traymond could not create a save file.\", \"Traymond\", MB_OK | MB_ICONERROR);\n exitApp();\n }\n \/\/ Check if we've crashed (i. e. there is a save file) during current uptime and\n \/\/ if there are windows to restore, in which case restore them and\n \/\/ display a reassuring message.\n if (GetLastError() == ERROR_ALREADY_EXISTS) {\n DWORD numbytes;\n DWORD fileSize = GetFileSize(saveFile, NULL);\n\n if (!fileSize) {\n return;\n };\n\n FILETIME saveFileWriteTime;\n GetFileTime(saveFile, NULL, NULL, &saveFileWriteTime);\n uint64_t writeTime = ((uint64_t)saveFileWriteTime.dwHighDateTime << 32 | (uint64_t)saveFileWriteTime.dwLowDateTime) \/ 10000;\n GetSystemTimeAsFileTime(&saveFileWriteTime);\n writeTime = (((uint64_t)saveFileWriteTime.dwHighDateTime << 32 | (uint64_t)saveFileWriteTime.dwLowDateTime) \/ 10000) - writeTime;\n\n if (GetTickCount64() < writeTime) {\n return;\n }\n\n std::vector contents = std::vector(fileSize);\n ReadFile(saveFile, &contents.front(), fileSize, &numbytes, NULL);\n char handle[10];\n int index = 0;\n for (size_t i = 0; i < fileSize; i++)\n {\n if (contents[i] != ',') {\n handle[index] = contents[i];\n index++;\n }\n else {\n index = 0;\n minimizeToTray(context, std::stoi(std::string(handle)));\n memset(handle, 0, sizeof(handle));\n }\n }\n std::string restore_message = \"Traymond had previously been terminated unexpectedly.\\n\\nRestored \" + \\\n std::to_string(context->iconIndex) + (context->iconIndex > 1 ? \" icons.\" : \" icon.\");\n MessageBox(NULL, restore_message.c_str(), \"Traymond\", MB_OK);\n }\n }\n\nLRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {\n\n TRCONTEXT* context = reinterpret_cast(GetWindowLongPtr(hwnd, GWLP_USERDATA));\n POINT pt;\n switch (uMsg)\n {\n case WM_ICON:\n if (LOWORD(lParam) == WM_LBUTTONDBLCLK) {\n showWindow(context, lParam);\n }\n break;\n case WM_OURICON:\n if (LOWORD(lParam) == WM_RBUTTONUP) {\n SetForegroundWindow(hwnd);\n GetCursorPos(&pt);\n TrackPopupMenuEx(context->trayMenu, \\\n (GetSystemMetrics(SM_MENUDROPALIGNMENT) ? TPM_RIGHTALIGN : TPM_LEFTALIGN) | TPM_BOTTOMALIGN, \\\n pt.x, pt.y, hwnd, NULL);\n }\n break;\n case WM_COMMAND:\n if (HIWORD(wParam) == 0) {\n switch LOWORD(wParam) {\n case SHOW_ALL_ID:\n showAllWindows(context);\n break;\n case EXIT_ID:\n exitApp();\n break;\n }\n }\n break;\n case WM_HOTKEY: \/\/ We only have one hotkey, so no need to check the message\n minimizeToTray(context, NULL);\n break;\n default:\n return DefWindowProc(hwnd, uMsg, wParam, lParam);\n }\n return 0;\n}\n\n#pragma warning( push )\n#pragma warning( disable : 4100 )\nint WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) {\n#pragma warning( pop )\n\n TRCONTEXT context = {};\n\n NOTIFYICONDATA icon = {};\n\n \/\/ Mutex to allow only one instance\n const char szUniqueNamedMutex[] = \"traymond_mutex\";\n HANDLE mutex = CreateMutex(NULL, TRUE, szUniqueNamedMutex);\n if (GetLastError() == ERROR_ALREADY_EXISTS)\n {\n MessageBox(NULL, \"Error! Another instance of Traymond is already running.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return 1;\n }\n\n BOOL bRet;\n MSG msg;\n\n const char CLASS_NAME[] = \"Traymond\";\n\n WNDCLASS wc = {};\n wc.lpfnWndProc = WindowProc;\n wc.hInstance = hInstance;\n wc.lpszClassName = CLASS_NAME;\n\n if (!RegisterClass(&wc)) {\n return 1;\n }\n\n context.mainWindow = CreateWindow(CLASS_NAME, NULL, NULL, 0, 0, 0, 0, HWND_MESSAGE, NULL, hInstance, NULL);\n\n if (!context.mainWindow) {\n return 1;\n }\n\n \/\/ Store our context in main window for retrieval by WindowProc\n SetWindowLongPtr(context.mainWindow, GWLP_USERDATA, reinterpret_cast(&context));\n\n if (!RegisterHotKey(context.mainWindow, 0, MOD_KEY | MOD_NOREPEAT, TRAY_KEY)) {\n MessageBox(NULL, \"Error! Could not register the hotkey.\", \"Traymond\", MB_OK | MB_ICONERROR);\n return 1;\n }\n\n createTrayIcon(context.mainWindow, hInstance, &icon);\n createTrayMenu(&context.trayMenu);\n startup(&context);\n\n while ((bRet = GetMessage(&msg, 0, 0, 0)) != 0)\n {\n if (bRet != -1) {\n DispatchMessage(&msg);\n }\n }\n \/\/ Clean up on exit;\n showAllWindows(&context);\n Shell_NotifyIcon(NIM_DELETE, &icon);\n ReleaseMutex(mutex);\n CloseHandle(mutex);\n CloseHandle(saveFile);\n DestroyMenu(context.trayMenu);\n DestroyWindow(context.mainWindow);\n DeleteFile(\"traymond.dat\"); \/\/ No save file means we have exited gracefully\n UnregisterHotKey(context.mainWindow, 0);\n return msg.wParam;\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this \nlist of conditions and the following disclaimer in the documentation and\/or \nother materials provided with the distribution.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*booksim_config.cpp\n *\n *Contains all the configurable parameters in a network\n *\n *\/\n\n\n#include \"booksim.hpp\"\n#include \"booksim_config.hpp\"\n\nBookSimConfig::BookSimConfig( )\n{ \n \/\/========================================================\n \/\/ Network options\n \/\/========================================================\n\n \/\/ Channel length listing file\n AddStrField( \"channel_file\", \"\" ) ;\n\n \/\/ Use read\/write request reply scheme\n \n _int_map[\"use_read_write\"] = 0;\n\n _int_map[\"read_request_begin_vc\"] = 0;\n _int_map[\"read_request_end_vc\"] = 5;\n\n _int_map[\"write_request_begin_vc\"] = 2;\n _int_map[\"write_request_end_vc\"] = 7;\n\n _int_map[\"read_reply_begin_vc\"] = 8;\n _int_map[\"read_reply_end_vc\"] = 13;\n\n _int_map[\"write_reply_begin_vc\"] = 10;\n _int_map[\"write_reply_end_vc\"] = 15;\n\n \/\/ Physical sub-networks\n _int_map[\"physical_subnetworks\"] = 1;\n\n \/\/ Control Injection of Packets into Replicated Networks\n _int_map[\"read_request_subnet\"] = 0;\n\n _int_map[\"read_reply_subnet\"] = 0;\n\n _int_map[\"write_request_subnet\"] = 0;\n\n _int_map[\"write_reply_subnet\"] = 0;\n\n \/\/==== Topology options =======================\n \/\/important\n AddStrField( \"topology\", \"torus\" );\n _int_map[\"k\"] = 8; \/\/network radix\n _int_map[\"n\"] = 2; \/\/network dimension\n _int_map[\"c\"] = 1; \/\/concentration\n AddStrField( \"routing_function\", \"none\" );\n _int_map[\"use_noc_latency\"] = 1;\n\n \/\/not critical\n _int_map[\"x\"] = 8; \/\/number of routers in X\n _int_map[\"y\"] = 8; \/\/number of routers in Y\n _int_map[\"xr\"] = 1; \/\/number of nodes per router in X only if c>1\n _int_map[\"yr\"] = 1; \/\/number of nodes per router in Y only if c>1\n _int_map[\"limit\"] = 0; \/\/how many of the nodes are actually used\n\n\n _int_map[\"link_failures\"] = 0; \/\/legacy\n _int_map[\"fail_seed\"] = 0; \/\/legacy\n\n \/\/==== Cmesh topology options =======================\n _int_map[\"express_channels\"] = 0; \/\/for Cmesh only, 0=no express channels\n \/\/==== Single-node options ===============================\n\n _int_map[\"in_ports\"] = 5;\n _int_map[\"out_ports\"] = 5;\n _int_map[\"voq\"] = 0; \/\/output queuing\n\n \/\/========================================================\n \/\/ Router options\n \/\/========================================================\n\n \/\/==== General options ===================================\n\n AddStrField( \"router\", \"iq\" ); \n\n _int_map[\"output_delay\"] = 0;\n _int_map[\"credit_delay\"] = 0;\n _float_map[\"internal_speedup\"] = 1.0;\n\n \/\/==== Input-queued ======================================\n\n \/\/ Control of virtual channel speculation\n _int_map[\"speculative\"] = 0 ;\n \n \/\/ what to use to inhibit speculative allocator grants?\n AddStrField(\"filter_spec_grants\", \"confl_nonspec_gnts\");\n\n _int_map[\"num_vcs\"] = 16; \n _int_map[\"vc_buf_size\"] = 8; \n _int_map[\"shared_buf_size\"] = 0;\n _int_map[\"dynamic_sharing\"] = 0;\n\n _int_map[\"wait_for_tail_credit\"] = 0; \/\/ reallocate a VC before a tail credit?\n _int_map[\"vc_busy_when_full\"] = 0; \/\/ mark VCs as in use when they have no credit available\n _int_map[\"vc_priority_donation\"] = 0; \/\/ allow high-priority flits to donate their priority to low-priority that they are queued up behind\n _int_map[\"replies_inherit_priority\"] = 0; \/\/ whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age\n\n _int_map[\"hold_switch_for_packet\"] = 0; \/\/ hold a switch config for the entire packet\n\n _int_map[\"input_speedup\"] = 1; \/\/ expansion of input ports into crossbar\n _int_map[\"output_speedup\"] = 1; \/\/ expansion of output ports into crossbar\n\n _int_map[\"routing_delay\"] = 1; \n _int_map[\"vc_alloc_delay\"] = 1; \n _int_map[\"sw_alloc_delay\"] = 1; \n _int_map[\"st_prepare_delay\"] = 0;\n _int_map[\"st_final_delay\"] = 1;\n\n \/\/==== Event-driven =====================================\n\n _int_map[\"vct\"] = 0; \n\n \/\/==== Allocators ========================================\n\n AddStrField( \"vc_allocator\", \"islip\" ); \n AddStrField( \"sw_allocator\", \"islip\" ); \n \n AddStrField( \"vc_alloc_arb_type\", \"round_robin\" );\n AddStrField( \"sw_alloc_arb_type\", \"round_robin\" );\n \n _int_map[\"alloc_iters\"] = 1;\n \n \/\/ dub: allow setting the number of iterations for each allocator separately\n \/\/ (a value of 0 indicates it should inherit its value from alloc_iters)\n _int_map[\"vc_alloc_iters\"] = 0;\n _int_map[\"sw_alloc_iters\"] = 0;\n\n \/\/==== Traffic ========================================\n\n AddStrField( \"traffic\", \"uniform\" );\n\n AddStrField( \"hotspot_nodes\", \"\" );\n AddStrField( \"hotspot_rates\", \"\" );\n\n AddStrField( \"combined_patterns\", \"\" );\n AddStrField( \"combined_rates\", \"\" );\n\n _int_map[\"perm_seed\"] = 0; \/\/ seed value for random permuation trafficpattern generator\n\n _float_map[\"injection_rate\"] = 0.1; \/\/if 0.0 assumes it is batch mode\n _int_map[\"injection_rate_uses_flits\"] = 0;\n\n _int_map[\"const_flits_per_packet\"] = 1; \/\/use read_request_size etc insted\n\n AddStrField( \"injection_process\", \"bernoulli\" );\n\n _float_map[\"burst_alpha\"] = 0.5; \/\/ burst interval\n _float_map[\"burst_beta\"] = 0.5; \/\/ burst length\n\n AddStrField( \"priority\", \"none\" ); \/\/ message priorities\n\n _int_map[\"batch_size\"] = 1000;\n _int_map[\"batch_count\"] = 1;\n _int_map[\"max_outstanding_requests\"] = 4;\n\n _int_map[\"read_request_size\"] = 1; \/\/flit per packet\n _int_map[\"write_request_size\"] = 1; \/\/flit per packet\n _int_map[\"read_reply_size\"] = 1; \/\/flit per packet\n _int_map[\"write_reply_size\"] = 1; \/\/flit per packet\n\n \/\/==== Simulation parameters ==========================\n\n \/\/ types:\n \/\/ latency - average + latency distribution for a particular injection rate\n \/\/ throughput - sustained throughput for a particular injection rate\n\n AddStrField( \"sim_type\", \"latency\" );\n\n _int_map[\"warmup_periods\"] = 3; \/\/ number of samples periods to \"warm-up\" the simulation\n\n _int_map[\"sample_period\"] = 1000; \/\/ how long between measurements\n _int_map[\"max_samples\"] = 10; \/\/ maximum number of sample periods in a simulation\n\n _float_map[\"latency_thres\"] = 500.0; \/\/ if avg. latency exceeds the threshold, assume unstable\n _float_map[\"warmup_thres\"] = 0.05; \/\/ consider warmed up once relative change in latency and throughput between successive iterations is smaller than this\n\n \/\/ consider converged once relative change in latency \/ throughput between successive iterations is smaller than this\n _float_map[\"stopping_thres\"] = 0.05;\n _float_map[\"acc_stopping_thres\"] = 0.05;\n\n _int_map[\"sim_count\"] = 1; \/\/ number of simulations to perform\n\n\n _int_map[\"include_queuing\"] =1; \/\/ non-zero includes source queuing latency\n\n \/\/ _int_map[\"reorder\"] = 0; \/\/ know what you're doing\n\n \/\/_int_map[\"flit_timing\"] = 0; \/\/ know what you're doing\n \/\/_int_map[\"split_packets\"] = 0; \/\/ know what you're doing\n\n _int_map[\"seed\"] = 0; \/\/random seed for simulation, e.g. traffic \n\n _int_map[\"print_activity\"] = 0;\n\n _int_map[\"print_csv_results\"] = 0;\n _int_map[\"print_vc_stats\"] = 0;\n\n _int_map[\"deadlock_warn_timeout\"] = 256;\n\n _int_map[\"drain_measured_only\"] = 0;\n\n _int_map[\"viewer_trace\"] = 0;\n\n AddStrField(\"watch_file\", \"\");\n \n AddStrField(\"watch_flits\", \"\");\n AddStrField(\"watch_packets\", \"\");\n\n AddStrField(\"watch_out\", \"\");\n\n AddStrField(\"stats_out\", \"\");\n AddStrField(\"flow_out\", \"\");\n \n \/\/==================Power model params=====================\n _int_map[\"sim_power\"] = 0;\n AddStrField(\"power_output_file\",\"pwr_tmp\");\n AddStrField(\"tech_file\", \"..\/utils\/temp\");\n _int_map[\"channel_width\"] = 128;\n _int_map[\"channel_sweep\"] = 0;\n\n \/\/==================Network file===========================\n AddStrField(\"network_file\",\"\");\n}\n\n\n#ifdef USE_GUI\n\n\/\/A list of important simulator for the booksim gui, anything else not listed here is still included\n\/\/but just not very organized\nvector< pair > > *BookSimConfig::GetImportantMap(){\n \/\/Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts\n vector< pair > > *important = new vector< pair > >;\n important->push_back( make_pair( \"Topology\", vector() ));\n (*important)[0].second.push_back(\"topology\");\n (*important)[0].second.push_back(\"k\");\n (*important)[0].second.push_back(\"n\");\n (*important)[0].second.push_back(\"c\");\n (*important)[0].second.push_back( \"routing_function\");\n (*important)[0].second.push_back(\"use_noc_latency\");\n\n important->push_back(make_pair(\"Router\", vector()));\n (*important)[1].second.push_back(\"router\");\n (*important)[1].second.push_back(\"num_vcs\");\n (*important)[1].second.push_back(\"vc_buf_size\");\n (*important)[1].second.push_back(\"routing_delay\");\n (*important)[1].second.push_back(\"vc_alloc_delay\");\n (*important)[1].second.push_back(\"sw_alloc_delay\");\n (*important)[1].second.push_back(\"st_prepare_delay\");\n (*important)[1].second.push_back(\"st_final_delay\");\n\n important->push_back(make_pair(\"Allocator\", vector()));\n (*important)[2].second.push_back(\"vc_allocator\");\n (*important)[2].second.push_back(\"vc_alloc_arb_type\");\n (*important)[2].second.push_back(\"sw_allocator\");\n (*important)[2].second.push_back(\"sw_alloc_arb_type\");\n (*important)[2].second.push_back( \"priority\");\n (*important)[2].second.push_back(\"speculative\");\n\n important->push_back(make_pair(\"Simulation\", vector()));\n (*important)[3].second.push_back(\"traffic\");\n (*important)[3].second.push_back(\"injection_rate\");\n (*important)[3].second.push_back(\"injection_rate_uses_flits\");\n (*important)[3].second.push_back(\"sim_type\");\n (*important)[3].second.push_back(\"latency_thres\");\n (*important)[3].second.push_back(\"const_flits_per_packet\");\n (*important)[3].second.push_back(\"injection_process\");\n (*important)[3].second.push_back(\"sample_period\");\n\n important->push_back(make_pair(\"Statistics\", vector()));\n (*important)[4].second.push_back(\"print_activity\");\n (*important)[4].second.push_back(\"print_csv_results\");\n (*important)[4].second.push_back(\"print_vc_stats\");\n (*important)[4].second.push_back(\"stats_out\");\n (*important)[4].second.push_back(\"sim_power\");\n (*important)[4].second.push_back(\"power_output_file\");\n\n\n return important;\n}\n\n#endif\n\nvector BookSimConfig::tokenize(string data) {\n const string separator = \"{,}\";\n vector result;\n size_t last_pos = data.find_first_not_of(separator);\n size_t pos = data.find_first_of(separator, last_pos);\n while(pos != string::npos || last_pos != string::npos) {\n result.push_back(data.substr(last_pos, pos - last_pos));\n last_pos = data.find_first_not_of(separator, pos);\n pos = data.find_first_of(separator, last_pos);\n }\n return result;\n}\n\nPowerConfig::PowerConfig( )\n{ \n\n _int_map[\"H_INVD2\"] = 0;\n _int_map[\"W_INVD2\"] = 0;\n _int_map[\"H_DFQD1\"] = 0;\n _int_map[\"W_DFQD1\"] = 0;\n _int_map[\"H_ND2D1\"] = 0;\n _int_map[\"W_ND2D1\"] = 0;\n _int_map[\"H_SRAM\"] = 0;\n _int_map[\"W_SRAM\"] = 0;\n _float_map[\"Vdd\"] = 0;\n _float_map[\"R\"] = 0;\n _float_map[\"IoffSRAM\"] = 0;\n _float_map[\"IoffP\"] = 0;\n _float_map[\"IoffN\"] = 0;\n _float_map[\"Cg_pwr\"] = 0;\n _float_map[\"Cd_pwr\"] = 0;\n _float_map[\"Cgdl\"] = 0;\n _float_map[\"Cg\"] = 0;\n _float_map[\"Cd\"] = 0;\n _float_map[\"LAMBDA\"] = 0;\n _float_map[\"MetalPitch\"] = 0;\n _float_map[\"Rw\"] = 0;\n _float_map[\"Cw_gnd\"] = 0;\n _float_map[\"Cw_cpl\"] = 0;\n _float_map[\"wire_length\"] = 0;\n\n}\nreorder parameters\/\/ $Id$\n\n\/*\nCopyright (c) 2007-2009, Trustees of The Leland Stanford Junior University\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this \nlist of conditions and the following disclaimer in the documentation and\/or \nother materials provided with the distribution.\nNeither the name of the Stanford University nor the names of its contributors \nmay be used to endorse or promote products derived from this software without \nspecific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND \nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED \nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE \nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR \nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES \n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; \nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON \nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT \n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS \nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n\/*booksim_config.cpp\n *\n *Contains all the configurable parameters in a network\n *\n *\/\n\n\n#include \"booksim.hpp\"\n#include \"booksim_config.hpp\"\n\nBookSimConfig::BookSimConfig( )\n{ \n \/\/========================================================\n \/\/ Network options\n \/\/========================================================\n\n \/\/ Channel length listing file\n AddStrField( \"channel_file\", \"\" ) ;\n\n \/\/ Physical sub-networks\n _int_map[\"physical_subnetworks\"] = 1;\n\n \/\/==== Topology options =======================\n \/\/important\n AddStrField( \"topology\", \"torus\" );\n _int_map[\"k\"] = 8; \/\/network radix\n _int_map[\"n\"] = 2; \/\/network dimension\n _int_map[\"c\"] = 1; \/\/concentration\n AddStrField( \"routing_function\", \"none\" );\n _int_map[\"use_noc_latency\"] = 1;\n\n \/\/not critical\n _int_map[\"x\"] = 8; \/\/number of routers in X\n _int_map[\"y\"] = 8; \/\/number of routers in Y\n _int_map[\"xr\"] = 1; \/\/number of nodes per router in X only if c>1\n _int_map[\"yr\"] = 1; \/\/number of nodes per router in Y only if c>1\n _int_map[\"limit\"] = 0; \/\/how many of the nodes are actually used\n\n\n _int_map[\"link_failures\"] = 0; \/\/legacy\n _int_map[\"fail_seed\"] = 0; \/\/legacy\n\n \/\/==== Cmesh topology options =======================\n _int_map[\"express_channels\"] = 0; \/\/for Cmesh only, 0=no express channels\n \/\/==== Single-node options ===============================\n\n _int_map[\"in_ports\"] = 5;\n _int_map[\"out_ports\"] = 5;\n _int_map[\"voq\"] = 0; \/\/output queuing\n\n \/\/========================================================\n \/\/ Router options\n \/\/========================================================\n\n \/\/==== General options ===================================\n\n AddStrField( \"router\", \"iq\" ); \n\n _int_map[\"output_delay\"] = 0;\n _int_map[\"credit_delay\"] = 0;\n _float_map[\"internal_speedup\"] = 1.0;\n\n \/\/==== Input-queued ======================================\n\n \/\/ Control of virtual channel speculation\n _int_map[\"speculative\"] = 0 ;\n \n \/\/ what to use to inhibit speculative allocator grants?\n AddStrField(\"filter_spec_grants\", \"confl_nonspec_gnts\");\n\n _int_map[\"num_vcs\"] = 16; \n _int_map[\"vc_buf_size\"] = 8; \n _int_map[\"shared_buf_size\"] = 0;\n _int_map[\"dynamic_sharing\"] = 0;\n\n _int_map[\"wait_for_tail_credit\"] = 0; \/\/ reallocate a VC before a tail credit?\n _int_map[\"vc_busy_when_full\"] = 0; \/\/ mark VCs as in use when they have no credit available\n _int_map[\"vc_priority_donation\"] = 0; \/\/ allow high-priority flits to donate their priority to low-priority that they are queued up behind\n _int_map[\"replies_inherit_priority\"] = 0; \/\/ whenusing request-reply traffic (use_read_write=1) with age-based priority, make replies inherit their corresponding requests' age\n\n _int_map[\"hold_switch_for_packet\"] = 0; \/\/ hold a switch config for the entire packet\n\n _int_map[\"input_speedup\"] = 1; \/\/ expansion of input ports into crossbar\n _int_map[\"output_speedup\"] = 1; \/\/ expansion of output ports into crossbar\n\n _int_map[\"routing_delay\"] = 1; \n _int_map[\"vc_alloc_delay\"] = 1; \n _int_map[\"sw_alloc_delay\"] = 1; \n _int_map[\"st_prepare_delay\"] = 0;\n _int_map[\"st_final_delay\"] = 1;\n\n \/\/==== Event-driven =====================================\n\n _int_map[\"vct\"] = 0; \n\n \/\/==== Allocators ========================================\n\n AddStrField( \"vc_allocator\", \"islip\" ); \n AddStrField( \"sw_allocator\", \"islip\" ); \n \n AddStrField( \"vc_alloc_arb_type\", \"round_robin\" );\n AddStrField( \"sw_alloc_arb_type\", \"round_robin\" );\n \n _int_map[\"alloc_iters\"] = 1;\n \n \/\/ dub: allow setting the number of iterations for each allocator separately\n \/\/ (a value of 0 indicates it should inherit its value from alloc_iters)\n _int_map[\"vc_alloc_iters\"] = 0;\n _int_map[\"sw_alloc_iters\"] = 0;\n\n \/\/==== Traffic ========================================\n\n AddStrField( \"traffic\", \"uniform\" );\n\n AddStrField( \"hotspot_nodes\", \"\" );\n AddStrField( \"hotspot_rates\", \"\" );\n\n AddStrField( \"combined_patterns\", \"\" );\n AddStrField( \"combined_rates\", \"\" );\n\n _int_map[\"perm_seed\"] = 0; \/\/ seed value for random permuation trafficpattern generator\n\n _float_map[\"injection_rate\"] = 0.1; \/\/if 0.0 assumes it is batch mode\n _int_map[\"injection_rate_uses_flits\"] = 0;\n\n _int_map[\"const_flits_per_packet\"] = 1; \/\/use read_request_size etc insted\n\n AddStrField( \"injection_process\", \"bernoulli\" );\n\n _float_map[\"burst_alpha\"] = 0.5; \/\/ burst interval\n _float_map[\"burst_beta\"] = 0.5; \/\/ burst length\n\n AddStrField( \"priority\", \"none\" ); \/\/ message priorities\n\n _int_map[\"batch_size\"] = 1000;\n _int_map[\"batch_count\"] = 1;\n _int_map[\"max_outstanding_requests\"] = 4;\n\n \/\/ Use read\/write request reply scheme\n _int_map[\"use_read_write\"] = 0;\n\n \/\/ Control assignment of packets to VCs\n _int_map[\"read_request_begin_vc\"] = 0;\n _int_map[\"read_request_end_vc\"] = 5;\n _int_map[\"write_request_begin_vc\"] = 2;\n _int_map[\"write_request_end_vc\"] = 7;\n _int_map[\"read_reply_begin_vc\"] = 8;\n _int_map[\"read_reply_end_vc\"] = 13;\n _int_map[\"write_reply_begin_vc\"] = 10;\n _int_map[\"write_reply_end_vc\"] = 15;\n\n \/\/ Control Injection of Packets into Replicated Networks\n _int_map[\"read_request_subnet\"] = 0;\n _int_map[\"read_reply_subnet\"] = 0;\n _int_map[\"write_request_subnet\"] = 0;\n _int_map[\"write_reply_subnet\"] = 0;\n\n \/\/ Set packet length in flits\n _int_map[\"read_request_size\"] = 1;\n _int_map[\"write_request_size\"] = 1;\n _int_map[\"read_reply_size\"] = 1;\n _int_map[\"write_reply_size\"] = 1;\n\n \/\/==== Simulation parameters ==========================\n\n \/\/ types:\n \/\/ latency - average + latency distribution for a particular injection rate\n \/\/ throughput - sustained throughput for a particular injection rate\n\n AddStrField( \"sim_type\", \"latency\" );\n\n _int_map[\"warmup_periods\"] = 3; \/\/ number of samples periods to \"warm-up\" the simulation\n\n _int_map[\"sample_period\"] = 1000; \/\/ how long between measurements\n _int_map[\"max_samples\"] = 10; \/\/ maximum number of sample periods in a simulation\n\n _float_map[\"latency_thres\"] = 500.0; \/\/ if avg. latency exceeds the threshold, assume unstable\n _float_map[\"warmup_thres\"] = 0.05; \/\/ consider warmed up once relative change in latency and throughput between successive iterations is smaller than this\n\n \/\/ consider converged once relative change in latency \/ throughput between successive iterations is smaller than this\n _float_map[\"stopping_thres\"] = 0.05;\n _float_map[\"acc_stopping_thres\"] = 0.05;\n\n _int_map[\"sim_count\"] = 1; \/\/ number of simulations to perform\n\n\n _int_map[\"include_queuing\"] =1; \/\/ non-zero includes source queuing latency\n\n \/\/ _int_map[\"reorder\"] = 0; \/\/ know what you're doing\n\n \/\/_int_map[\"flit_timing\"] = 0; \/\/ know what you're doing\n \/\/_int_map[\"split_packets\"] = 0; \/\/ know what you're doing\n\n _int_map[\"seed\"] = 0; \/\/random seed for simulation, e.g. traffic \n\n _int_map[\"print_activity\"] = 0;\n\n _int_map[\"print_csv_results\"] = 0;\n _int_map[\"print_vc_stats\"] = 0;\n\n _int_map[\"deadlock_warn_timeout\"] = 256;\n\n _int_map[\"drain_measured_only\"] = 0;\n\n _int_map[\"viewer_trace\"] = 0;\n\n AddStrField(\"watch_file\", \"\");\n \n AddStrField(\"watch_flits\", \"\");\n AddStrField(\"watch_packets\", \"\");\n\n AddStrField(\"watch_out\", \"\");\n\n AddStrField(\"stats_out\", \"\");\n AddStrField(\"flow_out\", \"\");\n \n \/\/==================Power model params=====================\n _int_map[\"sim_power\"] = 0;\n AddStrField(\"power_output_file\",\"pwr_tmp\");\n AddStrField(\"tech_file\", \"..\/utils\/temp\");\n _int_map[\"channel_width\"] = 128;\n _int_map[\"channel_sweep\"] = 0;\n\n \/\/==================Network file===========================\n AddStrField(\"network_file\",\"\");\n}\n\n\n#ifdef USE_GUI\n\n\/\/A list of important simulator for the booksim gui, anything else not listed here is still included\n\/\/but just not very organized\nvector< pair > > *BookSimConfig::GetImportantMap(){\n \/\/Vector of 5 categories, each category is a vector of potions. Maps don't work because it autosorts\n vector< pair > > *important = new vector< pair > >;\n important->push_back( make_pair( \"Topology\", vector() ));\n (*important)[0].second.push_back(\"topology\");\n (*important)[0].second.push_back(\"k\");\n (*important)[0].second.push_back(\"n\");\n (*important)[0].second.push_back(\"c\");\n (*important)[0].second.push_back( \"routing_function\");\n (*important)[0].second.push_back(\"use_noc_latency\");\n\n important->push_back(make_pair(\"Router\", vector()));\n (*important)[1].second.push_back(\"router\");\n (*important)[1].second.push_back(\"num_vcs\");\n (*important)[1].second.push_back(\"vc_buf_size\");\n (*important)[1].second.push_back(\"routing_delay\");\n (*important)[1].second.push_back(\"vc_alloc_delay\");\n (*important)[1].second.push_back(\"sw_alloc_delay\");\n (*important)[1].second.push_back(\"st_prepare_delay\");\n (*important)[1].second.push_back(\"st_final_delay\");\n\n important->push_back(make_pair(\"Allocator\", vector()));\n (*important)[2].second.push_back(\"vc_allocator\");\n (*important)[2].second.push_back(\"vc_alloc_arb_type\");\n (*important)[2].second.push_back(\"sw_allocator\");\n (*important)[2].second.push_back(\"sw_alloc_arb_type\");\n (*important)[2].second.push_back( \"priority\");\n (*important)[2].second.push_back(\"speculative\");\n\n important->push_back(make_pair(\"Simulation\", vector()));\n (*important)[3].second.push_back(\"traffic\");\n (*important)[3].second.push_back(\"injection_rate\");\n (*important)[3].second.push_back(\"injection_rate_uses_flits\");\n (*important)[3].second.push_back(\"sim_type\");\n (*important)[3].second.push_back(\"latency_thres\");\n (*important)[3].second.push_back(\"const_flits_per_packet\");\n (*important)[3].second.push_back(\"injection_process\");\n (*important)[3].second.push_back(\"sample_period\");\n\n important->push_back(make_pair(\"Statistics\", vector()));\n (*important)[4].second.push_back(\"print_activity\");\n (*important)[4].second.push_back(\"print_csv_results\");\n (*important)[4].second.push_back(\"print_vc_stats\");\n (*important)[4].second.push_back(\"stats_out\");\n (*important)[4].second.push_back(\"sim_power\");\n (*important)[4].second.push_back(\"power_output_file\");\n\n\n return important;\n}\n\n#endif\n\nvector BookSimConfig::tokenize(string data) {\n const string separator = \"{,}\";\n vector result;\n size_t last_pos = data.find_first_not_of(separator);\n size_t pos = data.find_first_of(separator, last_pos);\n while(pos != string::npos || last_pos != string::npos) {\n result.push_back(data.substr(last_pos, pos - last_pos));\n last_pos = data.find_first_not_of(separator, pos);\n pos = data.find_first_of(separator, last_pos);\n }\n return result;\n}\n\nPowerConfig::PowerConfig( )\n{ \n\n _int_map[\"H_INVD2\"] = 0;\n _int_map[\"W_INVD2\"] = 0;\n _int_map[\"H_DFQD1\"] = 0;\n _int_map[\"W_DFQD1\"] = 0;\n _int_map[\"H_ND2D1\"] = 0;\n _int_map[\"W_ND2D1\"] = 0;\n _int_map[\"H_SRAM\"] = 0;\n _int_map[\"W_SRAM\"] = 0;\n _float_map[\"Vdd\"] = 0;\n _float_map[\"R\"] = 0;\n _float_map[\"IoffSRAM\"] = 0;\n _float_map[\"IoffP\"] = 0;\n _float_map[\"IoffN\"] = 0;\n _float_map[\"Cg_pwr\"] = 0;\n _float_map[\"Cd_pwr\"] = 0;\n _float_map[\"Cgdl\"] = 0;\n _float_map[\"Cg\"] = 0;\n _float_map[\"Cd\"] = 0;\n _float_map[\"LAMBDA\"] = 0;\n _float_map[\"MetalPitch\"] = 0;\n _float_map[\"Rw\"] = 0;\n _float_map[\"Cw_gnd\"] = 0;\n _float_map[\"Cw_cpl\"] = 0;\n _float_map[\"wire_length\"] = 0;\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"builtin.hh\"\n#include \"util.hh\"\n#include \"number.hh\"\n#include \"procedure.hh\"\n#include \"lisp_ptr.hh\"\n#include \"eval.hh\"\n#include \"builtin_util.hh\"\n#include \"printer.hh\"\n\nusing namespace std;\nusing namespace Procedure;\n\nnamespace {\n\ntemplate\ninline void number_pred(Fun&& fun){\n auto arg = pick_args_1();\n auto num = arg.get();\n if(!num){\n VM.return_value = Lisp_ptr{false};\n return;\n }\n\n VM.return_value = Lisp_ptr{fun(num)};\n}\n\nvoid complexp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer;\n });\n}\n\nvoid realp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() <= Number::Type::real;\n });\n}\n\nvoid rationalp(){\n number_pred([](Number* n){\n return n->type() >= Number::Type::integer\n && n->type() < Number::Type::real;\n });\n}\n\nvoid integerp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid exactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::integer;\n });\n}\n\nvoid inexactp(){\n number_pred([](Number* n){\n return n->type() == Number::Type::complex\n || n->type() == Number::Type::real;\n });\n}\n\nvoid number_type_check_failed(const char* func_name, Lisp_ptr p){\n fprintf(zs::err, \"native func: %s: arg is not number! (%s)\\n\",\n func_name, stringify(p.tag()));\n VM.return_value = {};\n}\n\nstruct complex_found{\n bool operator()(const Number::complex_type&, const Number::complex_type&) const{\n fprintf(zs::err, \"native func: number compare: complex cannot be ordinated\\n\");\n return true;\n }\n};\n\ntemplate