text
stringlengths
1
1.05M
; A142301: Primes congruent to 21 mod 44. ; Submitted by Jon Maiga ; 109,197,241,373,461,593,769,857,1033,1297,1429,1693,1913,2089,2221,2309,2441,2617,2749,2837,2969,3541,3673,3761,4157,4201,4289,4421,4597,4729,4817,4861,4993,5081,5477,5521,5653,5741,6269,6577,6709,6841,7193,7237,7369,7457,7589,7853,8117,8161,8293,8513,8689,8821,9041,9173,9349,9437,9613,9833,10009,10141,10273,10889,11197,11329,11549,11593,11681,11813,12253,12473,12517,12781,13001,13177,13309,13397,13441,14057,14321,14629,14717,15289,15377,15641,15773,15817,16301,16433,16477,16741,16829,17093 mov $1,20 mov $2,$0 add $2,2 pow $2,2 lpb $2 sub $2,1 mov $3,$1 seq $3,10051 ; Characteristic function of primes: 1 if n is prime, else 0. sub $0,$3 add $1,44 mov $4,$0 max $4,0 cmp $4,$0 mul $2,$4 lpe mov $0,$1 sub $0,43
; CALLER LINKAGE FOR FUNCTION POINTERS SECTION code_clib PUBLIC vz_plot PUBLIC _vz_plot PUBLIC cplot PUBLIC _cplot EXTERN vz_plot_callee EXTERN ASMDISP_VZ_PLOT_CALLEE .vz_plot ._vz_plot .cplot ._cplot pop af pop bc pop de pop hl push hl push de push bc push af ld h,e jp vz_plot_callee + ASMDISP_VZ_PLOT_CALLEE
#include "mgos.h" #include <RHReliableDatagram.h> #include <RH_Serial.h> extern "C" { enum mgos_app_init_result mgos_app_init(void); } #define CLIENT_ADDRESS 1 #define SERVER_ADDRESS 255 //Broadcast address #define BROADCAST_PERIOD_MS 1000 //!!! Dont put these on the stack: uint8_t data[] = "Hello World!"; uint8_t buf[RH_SERIAL_MAX_MESSAGE_LEN]; /** * @brief A timer callback to send the broadcast messgae. * @param arg Arguments passed to the callback (Null in this case). */ static void tx_broadcast_poll_timer_cb(void *arg) { RHReliableDatagram *manager = (RHReliableDatagram *)arg; LOG(LL_INFO, ("%s: Client TX",__FUNCTION__) ); manager->sendtoWait(data, sizeof(data), SERVER_ADDRESS); (void) arg; } enum mgos_app_init_result mgos_app_init(void) { static RH_Serial driver(Serial); static RHReliableDatagram manager(driver, CLIENT_ADDRESS); Serial.begin( mgos_sys_config_get_rh_serial_baud() ); if( manager.init() ) { mgos_set_timer(BROADCAST_PERIOD_MS, MGOS_TIMER_REPEAT, tx_broadcast_poll_timer_cb, (void*)&manager); } else { LOG(LL_INFO, ("init failed") ); } return MGOS_APP_INIT_SUCCESS; }
; A010036: Sum of 2^n, ..., 2^(n+1) - 1. ; 1,5,22,92,376,1520,6112,24512,98176,392960,1572352,6290432,25163776,100659200,402644992,1610596352,6442418176,25769738240,103079084032,412316598272,1649266917376,6597068718080,26388276969472,105553112072192,422212456677376,1688849843486720,6755399407501312,27021597697114112,108086390922674176,432345563959132160,1729382256373399552,6917529026567340032,27670116108416843776,110680464437962342400,442721857760439304192,1770887431058937085952,7083549724270108082176,28334198897149151805440,113336795588734046175232,453347182355211062607872,1813388729421394006245376,7253554917686675536609280,29014219670748901169692672,116056878683000002725281792,464227514732008806994149376,1856910058928052820162641920,7427640235712246465022656512,29710560942849056228834803712,118842243771396365652827570176,475368975085585744086286991360,1901475900342343539295101386752,7605903601369375283080312389632,30423614405477503384121063243776,121694457621910018040083880345600,486777830487640081167534776123392,1947111321950560342684537613975552,7788445287802241406766947474866176,31153781151208965699125383937392640,124615124604835862940616723825426432,498460498419343452050697271453417472 mov $1,2 pow $1,$0 mul $1,3 bin $1,2 div $1,3 mov $0,$1
;****************************************************************************** ;* V210 SIMD pack ;* Copyright (c) 2014 Kieran Kunhya <kierank@obe.tv> ;* ;* This file is part of Libav. ;* ;* Libav is free software; you can redistribute it and/or ;* modify it under the terms of the GNU Lesser General Public ;* License as published by the Free Software Foundation; either ;* version 2.1 of the License, or (at your option) any later version. ;* ;* Libav is distributed in the hope that it will be useful, ;* but WITHOUT ANY WARRANTY; without even the implied warranty of ;* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ;* Lesser General Public License for more details. ;* ;* You should have received a copy of the GNU Lesser General Public ;* License along with Libav; if not, write to the Free Software ;* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ;****************************************************************************** %include "libavutil/x86/x86util.asm" SECTION_RODATA v210_enc_min_10: times 8 dw 0x4 v210_enc_max_10: times 8 dw 0x3fb v210_enc_luma_mult_10: dw 4,1,16,4,1,16,0,0 v210_enc_luma_shuf_10: db -1,0,1,-1,2,3,4,5,-1,6,7,-1,8,9,10,11 v210_enc_chroma_mult_10: dw 1,4,16,0,16,1,4,0 v210_enc_chroma_shuf_10: db 0,1,8,9,-1,2,3,-1,10,11,4,5,-1,12,13,-1 v210_enc_min_8: times 16 db 0x1 v210_enc_max_8: times 16 db 0xfe v210_enc_luma_shuf_8: db 6,-1,7,-1,8,-1,9,-1,10,-1,11,-1,-1,-1,-1,-1 v210_enc_luma_mult_8: dw 16,4,64,16,4,64,0,0 v210_enc_chroma_shuf1_8: db 0,-1,1,-1,2,-1,3,-1,8,-1,9,-1,10,-1,11,-1 v210_enc_chroma_shuf2_8: db 3,-1,4,-1,5,-1,7,-1,11,-1,12,-1,13,-1,15,-1 v210_enc_chroma_mult_8: dw 4,16,64,0,64,4,16,0 SECTION .text %macro v210_planar_pack_10 0 ; v210_planar_pack_10(const uint16_t *y, const uint16_t *u, const uint16_t *v, uint8_t *dst, ptrdiff_t width) cglobal v210_planar_pack_10, 5, 5, 4, y, u, v, dst, width lea r0, [yq+2*widthq] add uq, widthq add vq, widthq neg widthq mova m2, [v210_enc_min_10] mova m3, [v210_enc_max_10] .loop movu m0, [yq+2*widthq] CLIPW m0, m2, m3 movq m1, [uq+widthq] movhps m1, [vq+widthq] CLIPW m1, m2, m3 pmullw m0, [v210_enc_luma_mult_10] pshufb m0, [v210_enc_luma_shuf_10] pmullw m1, [v210_enc_chroma_mult_10] pshufb m1, [v210_enc_chroma_shuf_10] por m0, m1 movu [dstq], m0 add dstq, mmsize add widthq, 6 jl .loop RET %endmacro INIT_XMM ssse3 v210_planar_pack_10 %macro v210_planar_pack_8 0 ; v210_planar_pack_8(const uint8_t *y, const uint8_t *u, const uint8_t *v, uint8_t *dst, ptrdiff_t width) cglobal v210_planar_pack_8, 5, 5, 7, y, u, v, dst, width add yq, widthq shr widthq, 1 add uq, widthq add vq, widthq neg widthq mova m4, [v210_enc_min_8] mova m5, [v210_enc_max_8] pxor m6, m6 .loop movu m1, [yq+2*widthq] CLIPUB m1, m4, m5 punpcklbw m0, m1, m6 ; can't unpack high bytes in the same way because we process ; only six bytes at a time pshufb m1, [v210_enc_luma_shuf_8] pmullw m0, [v210_enc_luma_mult_8] pmullw m1, [v210_enc_luma_mult_8] pshufb m0, [v210_enc_luma_shuf_10] pshufb m1, [v210_enc_luma_shuf_10] movq m3, [uq+widthq] movhps m3, [vq+widthq] CLIPUB m3, m4, m5 ; shuffle and multiply to get the same packing as in 10-bit pshufb m2, m3, [v210_enc_chroma_shuf1_8] pshufb m3, [v210_enc_chroma_shuf2_8] pmullw m2, [v210_enc_chroma_mult_8] pmullw m3, [v210_enc_chroma_mult_8] pshufb m2, [v210_enc_chroma_shuf_10] pshufb m3, [v210_enc_chroma_shuf_10] por m0, m2 por m1, m3 movu [dstq], m0 movu [dstq+mmsize], m1 add dstq, 2*mmsize add widthq, 6 jl .loop RET %endmacro INIT_XMM ssse3 v210_planar_pack_8 INIT_XMM avx v210_planar_pack_8
#include <precompiled.h> /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE /// SOFTWARE. /// /// Header file #include <Dy/Builtin/Texture/ErrorBlue.h> #include <Dy/Helper/Type/DColorRGBA32.h> //! //! Local variables //! namespace { constexpr const dy::DColorRGBA32 _0 = dy::DColorRGBA32( 0, 0, 255); constexpr const dy::DColorRGBA32 _1 = dy::DColorRGBA32(255, 255, 255); } /// ::unnamed namespace //! //! Implementation //! namespace dy::builtin { void FDyBuiltinTextureErrorBlue::ConstructBuffer(_MOUT_ TBufferType& buffer, _MOUT_ PDyTextureInstanceMetaInfo& property) noexcept { property.mSpecifierName = FDyBuiltinTextureErrorBlue::sName; property.mTextureType = ETextureStyleType::D2; property.mTextureColorType = EDyImageColorFormatStyle::RGBA; property.mBuiltinBufferSize = DIVec2{ 16, 16 }; property.mTextureMapType_Deprecated = ETextureMapType::Diffuse; std::array<DColorRGBA32, 256> infoChunk = { // 0 4 8 12 /* 0 */_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_1,_1,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_1,_1,_1,_1,_0,_0,_0,_0,_0,_0, /* 4 */_0,_0,_0,_0,_0,_1,_1,_1,_1,_1,_1,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_1,_1,_1,_1,_1,_1,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_1,_1,_1,_1,_1,_1,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_1,_1,_1,_1,_1,_1,_0,_0,_0,_0,_0, /* 8 */_0,_0,_0,_0,_0,_0,_1,_1,_1,_1,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_1,_1,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_1,_1,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0, /* 12*/_0,_0,_0,_0,_0,_0,_0,_1,_1,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_1,_1,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0, /* */_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0,_0, }; buffer = ConvertToTU08VectorList(infoChunk); } }
; CRT0 stub for high RAM defc CLIB_SAM_IS_BASIC = 0 defc CRT_ORG_CODE = 0x8000 defc TAR__register_sp = 0xfd00 defc TAR__clib_exit_stack_size = 4 defc TAR__fputc_cons_generic = 1 defc CLIB_KBHIT_NOSTORE = 1 ; Where the screen is located defc SCREEN_BASE = 0x0000 PUBLIC THIS_FUNCTION_ONLY_WORKS_WITH_RAM_SUBTYPES defc THIS_FUNCTION_ONLY_WORKS_WITH_RAM_SUBTYPES = 1 PUBLIC __sam_graphics_pagein PUBLIC __sam_graphics_pageout INCLUDE "crt/classic/crt_rules.inc" org CRT_ORG_CODE program: di ; Make room for the atexit() stack INCLUDE "crt/classic/crt_init_sp.asm" INCLUDE "crt/classic/crt_init_atexit.asm" call crt0_init_bss ld (exitsp),sp ; Setup heap between end program and sp IF DEFINED_USING_amalloc INCLUDE "crt/classic/crt_init_amalloc.asm" ENDIF ; Now, page the screen into 0000-0x7fff ; Switch to mode 4 in a,(VMPR) ld b,a or @01100000 out (VMPR),a ld a,b and @00011111 or @00100000 ;Page video memory in low, turn off ROM out (LMPR),a ; We are in high RAM, we have to setup an interrupt handler ; (we don't have access to NMI here) ld hl,$fe00 ld de,$fe01 ld bc,257 ld (hl),$fd ldir ld a,195 ld ($fdfd),a ld hl,int_handler ld ($fdfe),hl ld a,0xfe ld i,a im 2 ei ; Entry to the user code call _main cleanup: call crt0_exit endloop: jr endloop ; Paging routines for graphics __sam_graphics_pagein: __sam_graphics_pageout: ret ; Interrupt handler EXTERN line_vectors EXTERN im1_vectors EXTERN asm_interrupt_handler int_handler: push af push hl in a,(STATUS) ld hl,im1_vectors bit 3,a ;Frame interrupt jr z,dispatch ld hl,line_vectors bit 0,a ;Line interrupt dispatch: call z, asm_interrupt_handler pop hl pop af ei ret l_dcal: jp (hl) INCLUDE "crt/classic/crt_runtime_selection.asm" INCLUDE "crt/classic/crt_section.asm"
; A158396: 729n^2 + 2n. ; 731,2920,6567,11672,18235,26256,35735,46672,59067,72920,88231,105000,123227,142912,164055,186656,210715,236232,263207,291640,321531,352880,385687,419952,455675,492856,531495,571592,613147,656160,700631,746560,793947,842792,893095,944856,998075,1052752,1108887,1166480,1225531,1286040,1348007,1411432,1476315,1542656,1610455,1679712,1750427,1822600,1896231,1971320,2047867,2125872,2205335,2286256,2368635,2452472,2537767,2624520,2712731,2802400,2893527,2986112,3080155,3175656,3272615,3371032,3470907,3572240,3675031,3779280,3884987,3992152,4100775,4210856,4322395,4435392,4549847,4665760,4783131,4901960,5022247,5143992,5267195,5391856,5517975,5645552,5774587,5905080,6037031,6170440,6305307,6441632,6579415,6718656,6859355,7001512,7145127,7290200,7436731,7584720,7734167,7885072,8037435,8191256,8346535,8503272,8661467,8821120,8982231,9144800,9308827,9474312,9641255,9809656,9979515,10150832,10323607,10497840,10673531,10850680,11029287,11209352,11390875,11573856,11758295,11944192,12131547,12320360,12510631,12702360,12895547,13090192,13286295,13483856,13682875,13883352,14085287,14288680,14493531,14699840,14907607,15116832,15327515,15539656,15753255,15968312,16184827,16402800,16622231,16843120,17065467,17289272,17514535,17741256,17969435,18199072,18430167,18662720,18896731,19132200,19369127,19607512,19847355,20088656,20331415,20575632,20821307,21068440,21317031,21567080,21818587,22071552,22325975,22581856,22839195,23097992,23358247,23619960,23883131,24147760,24413847,24681392,24950395,25220856,25492775,25766152,26040987,26317280,26595031,26874240,27154907,27437032,27720615,28005656,28292155,28580112,28869527,29160400,29452731,29746520,30041767,30338472,30636635,30936256,31237335,31539872,31843867,32149320,32456231,32764600,33074427,33385712,33698455,34012656,34328315,34645432,34964007,35284040,35605531,35928480,36252887,36578752,36906075,37234856,37565095,37896792,38229947,38564560,38900631,39238160,39577147,39917592,40259495,40602856,40947675,41293952,41641687,41990880,42341531,42693640,43047207,43402232,43758715,44116656,44476055,44836912,45199227,45563000 mov $3,$0 lpb $0 sub $0,1 add $1,3 lpe lpb $1 sub $1,1 add $2,3 lpe lpb $2 add $1,1 sub $2,1 lpe lpb $1 sub $1,1 add $2,3 lpe lpb $2 add $1,$2 sub $2,1 lpe mul $1,2 lpb $3 add $1,1433 sub $3,1 lpe add $1,731
; A170243: Number of reduced words of length n in Coxeter group on 42 generators S_i with relations (S_i)^2 = (S_i S_j)^40 = I. ; 1,42,1722,70602,2894682,118681962,4865960442,199504378122,8179679503002,335366859623082,13750041244546362,563751691026400842,23113819332082434522,947666592615379815402,38854330297230572431482 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,41 lpe mov $0,$2 div $0,41
; /***************************************************************************** ; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers * ; ***************************************************************************** ; * Copyright 2021 Marco Spedaletti (asimov@mclink.it) ; * ; * Licensed under the Apache License, Version 2.0 (the "License"); ; * you may not use this file eXcept in compliance with the License. ; * You may obtain a copy of the License at ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Unless required by applicable law or agreed to in writing, software ; * distributed under the License is distributed on an "AS IS" BASIS, ; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either eXpress or implied. ; * See the License for the specific language governing permissions and ; * limitations under the License. ; *---------------------------------------------------------------------------- ; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0 ; * (la "Licenza"); è proibito usare questo file se non in conformità alla ; * Licenza. Una copia della Licenza è disponibile all'indirizzo: ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Se non richiesto dalla legislazione vigente o concordato per iscritto, ; * il software distribuito nei termini della Licenza è distribuito ; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o ; * implicite. Consultare la Licenza per il testo specifico che regola le ; * autorizzazioni e le limitazioni previste dalla medesima. ; ****************************************************************************/ ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ;* * ;* MOVABLE OBJECTS UNDER Z80 (generic algorithms) * ;* * ;* by Marco Spedaletti * ;* * ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * MOB_COUNT = $10 MOBI: DB 0 MOBX: DW 0 MOBY: DW 0 MOBW: DW 0 MOBH: DW 0 MOBADDR: DW 0 MOBSIZE: DW 0 MOBLASTX: DW 0 MOBCOUNT: DB 0 ; DSDESCRIPTOR: ; PUSH HL ; PUSH BC ; LD A, B ; LD C, A ; LD A, 0 ; LD B, A ; PUSH BC ; POP HL ; ADD HL, HL ; ADD HL, HL ; ADD HL, HL ; ADD HL, HL ; ADD HL, HL ; PUSH HL ; POP DE ; LD HL, DESCRIPTORS ; ADD HL, DE ; PUSH HL ; POP IX ; POP BC ; POP HL ; RET ; ; Generic initialization ; ; MOBINIT(X:indeX,X,y,w,h,draw) ; MOBINIT: ; LD (MOBI), B ; ; Initialize status ; LD A, 0 ; LD (IX), A ; ; Initialize position ; LD A,(MOBX) ; LD (IX+1), A ; LD (IX+5), A ; LD A,(MOBX+1) ; LD (IX+2), A ; LD (IX+5), A ; LD A,(MOBY) ; LD (IX+3), A ; LD (IX+7), A ; LD A,(MOBY+1) ; LD (IX+4), A ; LD (IX+8), A ; ; Initialize size ; LD A,(MOBX) ; LD (IX+9), A ; LD A,(MOBH) ; LD (IX+10), A ; ; Save address of the given data. ; ; Note that specific chipset ; ; initialization can easily override this. ; LD A,(MOBADDR) ; LD (IX+11), A ; LD A,(MOBADDR+1) ; LD (IX+12), A ; ; Initialize to 0 the space for saving ; ; background (again, this is a chipset specific ; ; initialization routine). ; LD A, 0 ; LD (IX+13), A ; LD (IX+14), A ; ; Initialize the chipset specific part ; CALL MOBINITCS ; RET ; ; MOBSHOW(X:indeX) ; MOBSHOW: ; LDA A, (IX) ; OR A, 1 ; LD (IX), A ; RET ; ; MOBHIDE(X:indeX) ; MOBHIDE: ; LD A, (IX) ; AND A, $FE ; LD (IX), A ; RET ; ; MOBSAVE(X:indeX) -> chipset ; ; MOBRESTORE(X:indeX) -> chipset ; ; MOBDRAW(X:indeX) -> chipset ; MOBADJUST: ; LD A, (IX) ; AND A, 1 ; JR Z,MOBADJUSTN ; LD A, (IX) ; OR A, 3 ; LD (IX), A ; RET ; MOBADJUSTN: ; LD A, (IX) ; AND A, $FC ; LD (IX), A ; RET ; ; MOBAT(X:indeX, X, y) ; MOBAT: ; LD (MOBI), B ; LD A, (MOBX) ; LD (IX+1), A ; CP (IX+5) ; JR Z, MOBAT2 ; LD A, (IX) ; OR A, 4 ; LD (IX), A ; MOBAT2: ; LD A, (MOBX+1) ; LD (IX+2), A ; CP (IX+5) ; JR Z, MOBAT3 ; LD A, (IX) ; OR A, 4 ; LD (IX), A ; MOBAT3: ; LD A, (MOBY) ; LD (IX+3), A ; CP (IX+7) ; JR Z, MOBAT4 ; LD A, (IX) ; OR A, 8 ; LD (IX), A ; MOBAT4: ; LD A, (MOBY+1) ; LD (IX+4), A ; LD (IX+8), A ; CP #0 ; JR Z, MOBAT5 ; LD A, (IX) ; OR A, 8 ; LD (IX), A ; MOBAT5: ; CALL MOBATCS ; RET ; MOBALLOC: ; LD HL, (MOBADDRESS) ; LD DE, (MOBALLOCATED) ; ADD HL, DE ; LD MOBADDR, (HL) ; LD HL, (MOBALLOCATED) ; LD DE, (MOBSIZE) ; ADD HL, DE ; LD MOBADDR, (HL) ; RET ; MOBFREE: ; LD HL, (MOBALLOCATED) ; LD DE, (MOBSIZE) ; SUB HL, DE ; LD MOBADDR, (HL) ; RET ; MOBDESCRIPTORS: DEFS MOB_COUNT * 32 ; MOBALLOCATED: DQ $0 ; MOBRENDER: ; LD A, (MOBI) ; JR Z, MOBRENDERC ; JP VBL ; MOBRENDERC: ; ; X = 0 ; LD B, 0 ; MOBRENDERL1: ; ; take descriptor X ; LD A, (IX) ; ; unvisibled -> visibled? = $01 ; ; visibled? -> unvisibled = $02 ; ; moved + visibled? = $0D ; ; moved + unvisibled? = $0E ; ; moved? = $08 or $04 ; AND A, 3 ; CP 1 ; JR Z, MOBRENDERV1 ; CP 2 ; JR Z, MOBRENDERV1 ; ; retake descriptor X ; LD A, (IX) ; AND A, $C ; JR JZ, MOBRENDERV1 ; ; ++X ; INC B ; ; X < N ? ; LD A, B ; CP MOB_COUNT ; JR NZ, MOBRENDERL1 ; RET ; MOBRENDERV1: ; ; LASTX = X ; LD A, B ; LD (MOBLASTX), A ; ; X = N - 1 ; LD A, MOB_COUNT ; LD B, A ; DEC B ; MOBRENDERL2: ; ; previously visible? ; LD A, (IX) ; AND A, 2 ; JR Z, MOBRENDERV2 ; LD A, B ; LD (MOBI), A ; ; restore background at pX,py (w,h) save area ; CALL MOBRESTORE ; LD A, (MOBI) ; LD B, A ; ; adjust visibility flag ; CALL MOBADJUST ; MOBRENDERV2: ; ; update positions ; LD A, (IX+1) ; LD (IX+5), A ; LD A, (IX+2) ; LD (IX+6), A ; LD A, (IX+3) ; LD (IX+7), A ; LD A, (IX+4) ; LD (IX+8), A ; ; --X ; DEC B ; ; X >= LASTX ; CP B, MOBLASTX ; JR C, MOBRENDERL2 ; JR Z, MOBRENDERL2 ; ; Reset the save area to LAST X ; MOBRENDERV3: ; MOBRENDERL3: ; ; visible ? ; LD A, (IX) ; AND A, 1 ; CP #0 ; JR Z, MOBRENDERV4 ; LD A, B ; LD (MOBI), A ; ; save background at X,y (w,h) to save area ; CALL MOBSAVE ; LD A, (MOBI) ; LD B, A ; ; draw sprite at X,y (w,h) from draw area ; CALL MOBDRAW ; LD A, (MOBI) ; LD B, A ; ; adjust visibility flag ; CALL MOBADJUST ; LD A, (MOBI) ; LD B, A ; MOBRENDERV4: ; ; ++X ; DEC B ; ; X < N ? ; CP B, MOB_COUNT ; JR NC, MOBRENDERL3 ; RET
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ash/capture_mode/video_recording_watcher.h" #include <memory> #include "ash/capture_mode/capture_mode_constants.h" #include "ash/capture_mode/capture_mode_controller.h" #include "ash/capture_mode/capture_mode_metrics.h" #include "ash/shell.h" #include "ash/style/ash_color_provider.h" #include "ash/wm/desks/desks_util.h" #include "ash/wm/mru_window_tracker.h" #include "ash/wm/tablet_mode/tablet_mode_controller.h" #include "base/check.h" #include "base/check_op.h" #include "base/notreached.h" #include "base/time/time.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/aura/window.h" #include "ui/aura/window_tree_host.h" #include "ui/base/cursor/cursor_lookup.h" #include "ui/compositor/paint_recorder.h" #include "ui/display/screen.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point_f.h" #include "ui/gfx/geometry/rect_f.h" #include "ui/gfx/geometry/size_f.h" #include "ui/gfx/native_widget_types.h" #include "ui/gfx/scoped_canvas.h" #include "ui/wm/core/coordinate_conversion.h" #include "ui/wm/public/activation_client.h" namespace ash { namespace { // Recording is performed at a rate of 30 FPS. Any non-pressed/-released mouse // events that are too frequent will be throttled. We use the frame duration as // the minimum delay between any two successive such events that we use to // update the cursor overlay. constexpr base::TimeDelta kCursorEventsThrottleDelay = base::TimeDelta::FromHz(30); // Window resizes can be done on many intermediate steps. This delay is used to // throttle these resize events so that we send the final size of the window to // the recording service when it stabilizes. constexpr base::TimeDelta kWindowSizeChangeThrottleDelay = base::TimeDelta::FromMilliseconds(250); // Returns true if |window_1| and |window_2| are both windows that belong to // the same Desk. Note that it will return false for windows that don't belong // to any desk (such as always-on-top windows or PIPs). bool AreWindowsOnSameDesk(aura::Window* window_1, aura::Window* window_2) { auto* container_1 = desks_util::GetDeskContainerForContext(window_1); auto* container_2 = desks_util::GetDeskContainerForContext(window_2); return container_1 && container_2 && container_1 == container_2; } // Gets the mouse cursor location in the coordinates of the given |window|. Use // this if a mouse event is not available. gfx::PointF GetCursorLocationInWindow(aura::Window* window) { gfx::PointF cursor_point( display::Screen::GetScreen()->GetCursorScreenPoint()); wm::ConvertPointFromScreen(window, &cursor_point); return cursor_point; } // Gets the location of the given mouse |event| in the coordinates of the given // |window|. gfx::PointF GetEventLocationInWindow(aura::Window* window, const ui::MouseEvent& event) { aura::Window* target = static_cast<aura::Window*>(event.target()); gfx::PointF location = event.location_f(); if (target != window) aura::Window::ConvertPointToTarget(target, window, &location); return location; } // Returns the cursor overlay bounds as defined by the documentation of the // FrameSinkVideoCaptureOverlay. The bounds should be relative within the bounds // of the recorded frame sink (i.e. in the range [0.f, 1.f) for both cursor // origin and size). gfx::RectF GetCursorOverlayBounds( const aura::Window* recorded_window, const gfx::PointF& location_in_recorded_window, const gfx::PointF& cursor_hotspot, const SkBitmap& cursor_bitmap) { DCHECK(recorded_window); // Even when recording a non-root window, we use the bounds of the root // window, since it corresponds to the bounds of the source frame sink we are // recording. const auto window_size = recorded_window->GetRootWindow()->bounds().size(); if (window_size.IsEmpty()) return gfx::RectF(); gfx::RectF cursor_relative_bounds( location_in_recorded_window - cursor_hotspot.OffsetFromOrigin(), gfx::SizeF(cursor_bitmap.width(), cursor_bitmap.height())); cursor_relative_bounds.Scale(1.f / window_size.width(), 1.f / window_size.height()); return cursor_relative_bounds; } } // namespace // ----------------------------------------------------------------------------- // RecordedWindowRootObserver: // Defines an observer to observe the hierarchy changes of the root window under // which the recorded window resides. This is only constructed when performing a // window recording type. class RecordedWindowRootObserver : public aura::WindowObserver { public: RecordedWindowRootObserver(aura::Window* root, VideoRecordingWatcher* owner) : root_(root), owner_(owner) { DCHECK(root_); DCHECK(owner_); DCHECK(root_->IsRootWindow()); DCHECK_EQ(owner_->recording_source_, CaptureModeSource::kWindow); root_->AddObserver(this); } RecordedWindowRootObserver(const RecordedWindowRootObserver&) = delete; RecordedWindowRootObserver& operator=(const RecordedWindowRootObserver&) = delete; ~RecordedWindowRootObserver() override { root_->RemoveObserver(this); } // aura::WindowObserver: void OnWindowHierarchyChanged(const HierarchyChangeParams& params) override { DCHECK_EQ(params.receiver, root_); owner_->OnRootHierarchyChanged(params.target); } void OnWindowDestroying(aura::Window* window) override { // We should never get here, as the recorded window gets moved to a // different display before the root of another is destroyed. So this root // observer should have been destroyed already. NOTREACHED(); } private: aura::Window* const root_; VideoRecordingWatcher* const owner_; }; // ----------------------------------------------------------------------------- // VideoRecordingWatcher: VideoRecordingWatcher::VideoRecordingWatcher( CaptureModeController* controller, aura::Window* window_being_recorded, mojo::PendingRemote<viz::mojom::FrameSinkVideoCaptureOverlay> cursor_capture_overlay) : controller_(controller), cursor_manager_(Shell::Get()->cursor_manager()), window_being_recorded_(window_being_recorded), current_root_(window_being_recorded->GetRootWindow()), recording_source_(controller_->source()), cursor_capture_overlay_remote_(std::move(cursor_capture_overlay)) { DCHECK(controller_); DCHECK(window_being_recorded_); DCHECK(current_root_); DCHECK(controller_->is_recording_in_progress()); if (!window_being_recorded_->IsRootWindow()) { DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); non_root_window_capture_request_ = window_being_recorded_->MakeWindowCapturable(); root_observer_ = std::make_unique<RecordedWindowRootObserver>(current_root_, this); Shell::Get()->activation_client()->AddObserver(this); } else { // We only need to observe the changes in the state of the software- // composited cursor when recording a root window (i.e. fullscreen or // partial region capture), since the software cursor is in the layer // subtree of the root window, and will be captured by the frame sink video // capturer automatically without the need for the cursor overlay. In this // case we need to avoid producing a video with two overlapping cursors. // When recording a window however, the software cursor is not in its layer // subtree, and has to always be captured using the cursor overlay. auto* cursor_window_controller = Shell::Get()->window_tree_host_manager()->cursor_window_controller(); // Note that the software cursor might have already been enabled prior to // the recording starting. force_cursor_overlay_hidden_ = cursor_window_controller->is_cursor_compositing_enabled(); cursor_window_controller->AddObserver(this); } if (recording_source_ == CaptureModeSource::kRegion) partial_region_bounds_ = controller_->user_capture_region(); display::Screen::GetScreen()->AddObserver(this); window_being_recorded_->AddObserver(this); TabletModeController::Get()->AddObserver(this); // Note the following: // 1- We add |this| as a pre-target handler of the |window_being_recorded_| as // opposed to |Env|. This ensures that we only get mouse events when the // window being recorded is the target. This is more efficient since we // won't get any event when the curosr is in a different display, or // targeting a different window. // 2- We use the |kAccessibility| priority to ensure that we get these events // before other pre-target handlers can consume them (e.g. when opening a // capture mode session to take a screenshot while recording a video). window_being_recorded_->AddPreTargetHandler( this, ui::EventTarget::Priority::kAccessibility); } VideoRecordingWatcher::~VideoRecordingWatcher() { DCHECK(window_being_recorded_); window_being_recorded_->RemovePreTargetHandler(this); TabletModeController::Get()->RemoveObserver(this); if (recording_source_ == CaptureModeSource::kWindow) { Shell::Get()->activation_client()->RemoveObserver(this); } else { Shell::Get() ->window_tree_host_manager() ->cursor_window_controller() ->RemoveObserver(this); } display::Screen::GetScreen()->RemoveObserver(this); window_being_recorded_->RemoveObserver(this); } void VideoRecordingWatcher::OnWindowParentChanged(aura::Window* window, aura::Window* parent) { DCHECK_EQ(window, window_being_recorded_); DCHECK(controller_->is_recording_in_progress()); DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); UpdateLayerStackingAndDimmers(); } void VideoRecordingWatcher::OnWindowVisibilityChanged(aura::Window* window, bool visible) { if (window == window_being_recorded_) UpdateShouldPaintLayer(); } void VideoRecordingWatcher::OnWindowBoundsChanged( aura::Window* window, const gfx::Rect& old_bounds, const gfx::Rect& new_bounds, ui::PropertyChangeReason reason) { DCHECK(controller_->is_recording_in_progress()); if (recording_source_ != CaptureModeSource::kWindow) return; // We care only about size changes, since the location of the window won't // affect the recorded video frames of it, however, the size of the window // affects the size of the frames. if (old_bounds.size() == new_bounds.size()) return; window_size_change_throttle_timer_.Start( FROM_HERE, kWindowSizeChangeThrottleDelay, this, &VideoRecordingWatcher::OnWindowSizeChangeThrottleTimerFiring); } void VideoRecordingWatcher::OnWindowOpacitySet( aura::Window* window, ui::PropertyChangeReason reason) { if (window == window_being_recorded_) UpdateShouldPaintLayer(); } void VideoRecordingWatcher::OnWindowStackingChanged(aura::Window* window) { DCHECK_EQ(window, window_being_recorded_); DCHECK(controller_->is_recording_in_progress()); DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); UpdateLayerStackingAndDimmers(); } void VideoRecordingWatcher::OnWindowDestroying(aura::Window* window) { DCHECK_EQ(window, window_being_recorded_); DCHECK(controller_->is_recording_in_progress()); // EndVideoRecording() destroys |this|. No need to remove observer here, since // it will be done in the destructor. controller_->EndVideoRecording(EndRecordingReason::kDisplayOrWindowClosing); } void VideoRecordingWatcher::OnWindowDestroyed(aura::Window* window) { DCHECK_EQ(window, window_being_recorded_); // We should never get here, since OnWindowDestroying() calls // EndVideoRecording() which deletes us. NOTREACHED(); } void VideoRecordingWatcher::OnWindowRemovingFromRootWindow( aura::Window* window, aura::Window* new_root) { DCHECK_EQ(window, window_being_recorded_); DCHECK(controller_->is_recording_in_progress()); DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); root_observer_.reset(); current_root_ = new_root; if (!new_root) { // EndVideoRecording() destroys |this|. controller_->EndVideoRecording(EndRecordingReason::kDisplayOrWindowClosing); return; } root_observer_ = std::make_unique<RecordedWindowRootObserver>(current_root_, this); controller_->OnRecordedWindowChangingRoot(window_being_recorded_, new_root); } void VideoRecordingWatcher::OnPaintLayer(const ui::PaintContext& context) { if (!should_paint_layer_) return; DCHECK_NE(recording_source_, CaptureModeSource::kFullscreen); ui::PaintRecorder recorder(context, layer()->size()); gfx::Canvas* canvas = recorder.canvas(); auto* color_provider = AshColorProvider::Get(); const SkColor dimming_color = color_provider->GetShieldLayerColor( AshColorProvider::ShieldLayerType::kShield40); canvas->DrawColor(dimming_color); // We don't draw a region border around the recorded window. We just paint the // above shield as a backdrop. if (recording_source_ == CaptureModeSource::kWindow) return; gfx::ScopedCanvas scoped_canvas(canvas); const float dsf = canvas->UndoDeviceScaleFactor(); gfx::Rect region = gfx::ScaleToEnclosingRect(partial_region_bounds_, dsf); region.Inset(-capture_mode::kCaptureRegionBorderStrokePx, -capture_mode::kCaptureRegionBorderStrokePx); canvas->FillRect(region, SK_ColorTRANSPARENT, SkBlendMode::kClear); // Draw the region border. cc::PaintFlags border_flags; border_flags.setColor(capture_mode::kRegionBorderColor); border_flags.setStyle(cc::PaintFlags::kStroke_Style); border_flags.setStrokeWidth(capture_mode::kCaptureRegionBorderStrokePx); canvas->DrawRect(gfx::RectF(region), border_flags); } void VideoRecordingWatcher::OnWindowActivated(ActivationReason reason, aura::Window* gained_active, aura::Window* lost_active) { DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); UpdateLayerStackingAndDimmers(); } void VideoRecordingWatcher::OnDisplayMetricsChanged( const display::Display& display, uint32_t metrics) { if (recording_source_ == CaptureModeSource::kFullscreen) return; if (!(metrics & (DISPLAY_METRIC_BOUNDS | DISPLAY_METRIC_ROTATION | DISPLAY_METRIC_DEVICE_SCALE_FACTOR))) { return; } const int64_t display_id = display::Screen::GetScreen()->GetDisplayNearestWindow(current_root_).id(); if (display_id != display.id()) return; const auto& root_bounds = current_root_->bounds(); controller_->PushNewRootSizeToRecordingService(root_bounds.size()); DCHECK(layer()); layer()->SetBounds(root_bounds); } void VideoRecordingWatcher::OnDimmedWindowDestroying( aura::Window* dimmed_window) { dimmers_.erase(dimmed_window); } void VideoRecordingWatcher::OnDimmedWindowParentChanged( aura::Window* dimmed_window) { // If the dimmed window moves to another display or a different desk, we no // longer dim it. if (dimmed_window->GetRootWindow() != current_root_ || !AreWindowsOnSameDesk(dimmed_window, window_being_recorded_)) { dimmers_.erase(dimmed_window); } } void VideoRecordingWatcher::OnMouseEvent(ui::MouseEvent* event) { switch (event->type()) { case ui::ET_MOUSEWHEEL: case ui::ET_MOUSE_CAPTURE_CHANGED: return; case ui::ET_MOUSE_PRESSED: case ui::ET_MOUSE_RELEASED: // Pressed/released events are important, so we handle them immediately. UpdateCursorOverlayNow( GetEventLocationInWindow(window_being_recorded_, *event)); return; default: UpdateOrThrottleCursorOverlay( GetEventLocationInWindow(window_being_recorded_, *event)); } } void VideoRecordingWatcher::OnTabletModeStarted() { UpdateCursorOverlayNow(gfx::PointF()); } void VideoRecordingWatcher::OnTabletModeEnded() { UpdateCursorOverlayNow(GetCursorLocationInWindow(window_being_recorded_)); } void VideoRecordingWatcher::OnCursorCompositingStateChanged(bool enabled) { DCHECK_NE(recording_source_, CaptureModeSource::kWindow); force_cursor_overlay_hidden_ = enabled; UpdateCursorOverlayNow( force_cursor_overlay_hidden_ ? gfx::PointF() : GetCursorLocationInWindow(window_being_recorded_)); } bool VideoRecordingWatcher::IsWindowDimmedForTesting( aura::Window* window) const { return dimmers_.contains(window); } void VideoRecordingWatcher::BindCursorOverlayForTesting( mojo::PendingRemote<viz::mojom::FrameSinkVideoCaptureOverlay> overlay) { cursor_capture_overlay_remote_.reset(); cursor_capture_overlay_remote_.Bind(std::move(overlay)); } void VideoRecordingWatcher::FlushCursorOverlayForTesting() { cursor_capture_overlay_remote_.FlushForTesting(); } void VideoRecordingWatcher::SendThrottledWindowSizeChangedNowForTesting() { window_size_change_throttle_timer_.FireNow(); } void VideoRecordingWatcher::SetLayer(std::unique_ptr<ui::Layer> layer) { if (layer) { layer->set_delegate(this); layer->SetName("Recording Shield"); } LayerOwner::SetLayer(std::move(layer)); UpdateShouldPaintLayer(); UpdateLayerStackingAndDimmers(); } void VideoRecordingWatcher::OnRootHierarchyChanged(aura::Window* target) { DCHECK(controller_->is_recording_in_progress()); DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); if (target != window_being_recorded_ && !dimmers_.contains(target) && CanIncludeWindowInMruList(target)) { UpdateLayerStackingAndDimmers(); } } bool VideoRecordingWatcher::CalculateShouldPaintLayer() const { if (recording_source_ == CaptureModeSource::kFullscreen) return false; if (recording_source_ == CaptureModeSource::kRegion) return true; DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); return window_being_recorded_->TargetVisibility() && window_being_recorded_->layer()->GetTargetVisibility() && window_being_recorded_->layer()->GetTargetOpacity() > 0; } void VideoRecordingWatcher::UpdateShouldPaintLayer() { const bool new_value = CalculateShouldPaintLayer(); if (new_value == should_paint_layer_) return; should_paint_layer_ = new_value; if (!should_paint_layer_) { // If we're not painting the shield, we don't need the individual dimmers // either. dimmers_.clear(); } if (layer()) layer()->SchedulePaint(layer()->bounds()); } void VideoRecordingWatcher::UpdateLayerStackingAndDimmers() { if (!layer()) return; DCHECK_NE(recording_source_, CaptureModeSource::kFullscreen); const bool is_recording_window = recording_source_ == CaptureModeSource::kWindow; ui::Layer* new_parent = is_recording_window ? window_being_recorded_->layer()->parent() : current_root_->GetChildById(kShellWindowId_OverlayContainer) ->layer(); ui::Layer* old_parent = layer()->parent(); DCHECK(new_parent || is_recording_window); if (!new_parent && old_parent) { // If the window gets removed from the hierarchy, we remove the shield layer // too, as well as any dimming of windows we have. old_parent->Remove(layer()); dimmers_.clear(); return; } if (new_parent != old_parent) { // We get here the first time we parent the shield layer under the overlay // container when we're recording a partial region, or when recording a // window, and it gets moved to another display, or moved to a different // desk. new_parent->Add(layer()); layer()->SetBounds(current_root_->bounds()); } // When recording a partial region, the shield layer is stacked at the top of // everything in the overlay container. if (!is_recording_window) { new_parent->StackAtTop(layer()); return; } // However, when recording a window, we stack the shield layer below the // recorded window's layer. This takes care of dimming any windows below the // recorded window in the z-order. new_parent->StackBelow(layer(), window_being_recorded_->layer()); // If the shield is not painted, all the individual dimmers should be removed. if (!should_paint_layer_) { dimmers_.clear(); return; } // For windows that are above the recorded window in the z-order and on the // same display, they're dimmed separately. const SkColor dimming_color = AshColorProvider::Get()->GetShieldLayerColor( AshColorProvider::ShieldLayerType::kShield40); // We use |kAllDesks| here for the following reasons: // 1- A dimmed window can move out from the desk where the window being // recorded is (either by keyboard shortcut or drag and drop in overview). // 2- The recorded window itself can move out from the active desk to an // inactive desk that has other windows. // In (1), we want to remove the dimmers of those windows that moved out. // In (2), we want to remove the dimmers of the window on the active desk, and // create ones for the windows in the inactive desk (if any of them is above // the recorded window). const auto mru_windows = Shell::Get()->mru_window_tracker()->BuildWindowListIgnoreModal( DesksMruType::kAllDesks); bool did_find_recorded_window = false; // Note that the order of |mru_windows| are from top-most first. for (auto* window : mru_windows) { if (window == window_being_recorded_) { did_find_recorded_window = true; continue; } // No need to dim windows that are below the window being recorded in // z-order, or those on other displays, or other desks. if (did_find_recorded_window || window->GetRootWindow() != current_root_ || !AreWindowsOnSameDesk(window, window_being_recorded_)) { dimmers_.erase(window); continue; } auto& dimmer = dimmers_[window]; if (!dimmer) { dimmer = std::make_unique<WindowDimmer>(window, /*animate=*/false, this); dimmer->SetDimColor(dimming_color); dimmer->window()->Show(); } } } gfx::NativeCursor VideoRecordingWatcher::GetCurrentCursor() const { const auto cursor = cursor_manager_->GetCursor(); // See the documentation in cursor_type.mojom. |kNull| is treated exactly as // |kPointer|. return (cursor.type() == ui::mojom::CursorType::kNull) ? gfx::NativeCursor(ui::mojom::CursorType::kPointer) : cursor; } void VideoRecordingWatcher::UpdateOrThrottleCursorOverlay( const gfx::PointF& location) { if (cursor_events_throttle_timer_.IsRunning()) { throttled_cursor_location_ = location; return; } UpdateCursorOverlayNow(location); cursor_events_throttle_timer_.Start( FROM_HERE, kCursorEventsThrottleDelay, this, &VideoRecordingWatcher::OnCursorThrottleTimerFiring); } void VideoRecordingWatcher::UpdateCursorOverlayNow( const gfx::PointF& location) { // Cancel any pending throttled event. cursor_events_throttle_timer_.Stop(); throttled_cursor_location_.reset(); if (!cursor_capture_overlay_remote_) return; if (force_cursor_overlay_hidden_ || TabletModeController::Get()->InTabletMode()) { HideCursorOverlay(); return; } const gfx::RectF window_local_bounds( gfx::SizeF(window_being_recorded_->bounds().size())); if (!window_local_bounds.Contains(location)) { HideCursorOverlay(); return; } const gfx::NativeCursor cursor = GetCurrentCursor(); DCHECK_NE(cursor.type(), ui::mojom::CursorType::kNull); const SkBitmap cursor_image = ui::GetCursorBitmap(cursor); const gfx::RectF cursor_overlay_bounds = GetCursorOverlayBounds( window_being_recorded_, location, gfx::PointF(ui::GetCursorHotspot(cursor)), cursor_image); if (cursor != last_cursor_) { if (cursor_image.drawsNothing()) { last_cursor_ = gfx::NativeCursor(); HideCursorOverlay(); return; } last_cursor_ = cursor; last_cursor_overlay_bounds_ = cursor_overlay_bounds; cursor_capture_overlay_remote_->SetImageAndBounds( cursor_image, last_cursor_overlay_bounds_); return; } if (last_cursor_overlay_bounds_ == cursor_overlay_bounds) return; last_cursor_overlay_bounds_ = cursor_overlay_bounds; cursor_capture_overlay_remote_->SetBounds(last_cursor_overlay_bounds_); } void VideoRecordingWatcher::HideCursorOverlay() { DCHECK(cursor_capture_overlay_remote_); // No need to rehide if already hidden. if (last_cursor_overlay_bounds_ == gfx::RectF()) return; last_cursor_overlay_bounds_ = gfx::RectF(); cursor_capture_overlay_remote_->SetBounds(last_cursor_overlay_bounds_); } void VideoRecordingWatcher::OnCursorThrottleTimerFiring() { if (throttled_cursor_location_) UpdateCursorOverlayNow(*throttled_cursor_location_); } void VideoRecordingWatcher::OnWindowSizeChangeThrottleTimerFiring() { DCHECK(controller_->is_recording_in_progress()); DCHECK_EQ(recording_source_, CaptureModeSource::kWindow); controller_->OnRecordedWindowSizeChanged( window_being_recorded_->bounds().size()); } } // namespace ash
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "intro.h" #include "ui_intro.h" #include "guiutil.h" #include "util.h" #include <boost/filesystem.hpp> #include <QFileDialog> #include <QMessageBox> #include <QSettings> /* Minimum free space (in bytes) needed for data directory */ static const uint64_t GB_BYTES = 1000000000LL; static const uint64_t BLOCK_CHAIN_SIZE = 1LL * GB_BYTES; /* Check free space asynchronously to prevent hanging the UI thread. Up to one request to check a path is in flight to this thread; when the check() function runs, the current path is requested from the associated Intro object. The reply is sent back through a signal. This ensures that no queue of checking requests is built up while the user is still entering the path, and that always the most recently entered path is checked as soon as the thread becomes available. */ class FreespaceChecker : public QObject { Q_OBJECT public: FreespaceChecker(Intro* intro); enum Status { ST_OK, ST_ERROR }; public slots: void check(); signals: void reply(int status, const QString& message, quint64 available); private: Intro* intro; }; #include "intro.moc" FreespaceChecker::FreespaceChecker(Intro* intro) { this->intro = intro; } void FreespaceChecker::check() { namespace fs = boost::filesystem; QString dataDirStr = intro->getPathToCheck(); fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr); uint64_t freeBytesAvailable = 0; int replyStatus = ST_OK; QString replyMessage = tr("A new data directory will be created."); /* Find first parent that exists, so that fs::space does not fail */ fs::path parentDir = dataDir; fs::path parentDirOld = fs::path(); while (parentDir.has_parent_path() && !fs::exists(parentDir)) { parentDir = parentDir.parent_path(); /* Check if we make any progress, break if not to prevent an infinite loop here */ if (parentDirOld == parentDir) break; parentDirOld = parentDir; } try { freeBytesAvailable = fs::space(parentDir).available; if (fs::exists(dataDir)) { if (fs::is_directory(dataDir)) { QString separator = "<code>" + QDir::toNativeSeparators("/") + tr("name") + "</code>"; replyStatus = ST_OK; replyMessage = tr("Directory already exists. Add %1 if you intend to create a new directory here.").arg(separator); } else { replyStatus = ST_ERROR; replyMessage = tr("Path already exists, and is not a directory."); } } } catch (fs::filesystem_error& e) { /* Parent directory does not exist or is not accessible */ replyStatus = ST_ERROR; replyMessage = tr("Cannot create data directory here."); } emit reply(replyStatus, replyMessage, freeBytesAvailable); } Intro::Intro(QWidget* parent) : QDialog(parent), ui(new Ui::Intro), thread(0), signalled(false) { ui->setupUi(this); ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE / GB_BYTES)); startThread(); } Intro::~Intro() { delete ui; /* Ensure thread is finished before it is deleted */ emit stopThread(); thread->wait(); } QString Intro::getDataDirectory() { return ui->dataDirectory->text(); } void Intro::setDataDirectory(const QString& dataDir) { ui->dataDirectory->setText(dataDir); if (dataDir == getDefaultDataDirectory()) { ui->dataDirDefault->setChecked(true); ui->dataDirectory->setEnabled(false); ui->ellipsisButton->setEnabled(false); } else { ui->dataDirCustom->setChecked(true); ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } } QString Intro::getDefaultDataDirectory() { return GUIUtil::boostPathToQString(GetDefaultDataDir()); } bool Intro::pickDataDirectory() { namespace fs = boost::filesystem; QSettings settings; /* If data directory provided on command line, no need to look at settings or show a picking dialog */ if (!GetArg("-datadir", "").empty()) return true; /* 1) Default data directory for operating system */ QString dataDir = getDefaultDataDirectory(); /* 2) Allow QSettings to override default dir */ dataDir = settings.value("strDataDir", dataDir).toString(); if (!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg("-choosedatadir", false)) { /* If current default data directory does not exist, let the user choose one */ Intro intro; intro.setDataDirectory(dataDir); intro.setWindowIcon(QIcon(":icons/bitcoin")); while (true) { if (!intro.exec()) { /* Cancel clicked */ return false; } dataDir = intro.getDataDirectory(); try { TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir)); break; } catch (fs::filesystem_error& e) { QMessageBox::critical(0, tr("Smrtc Core"), tr("Error: Specified data directory \"%1\" cannot be created.").arg(dataDir)); /* fall through, back to choosing screen */ } } settings.setValue("strDataDir", dataDir); } /* Only override -datadir if different from the default, to make it possible to * override -datadir in the smrtc.conf file in the default data directory * (to be consistent with smrtcd behavior) */ if (dataDir != getDefaultDataDirectory()) SoftSetArg("-datadir", GUIUtil::qstringToBoostPath(dataDir).string()); // use OS locale for path setting return true; } void Intro::setStatus(int status, const QString& message, quint64 bytesAvailable) { switch (status) { case FreespaceChecker::ST_OK: ui->errorMessage->setText(message); ui->errorMessage->setStyleSheet(""); break; case FreespaceChecker::ST_ERROR: ui->errorMessage->setText(tr("Error") + ": " + message); ui->errorMessage->setStyleSheet("QLabel { color: #800000 }"); break; } /* Indicate number of bytes available */ if (status == FreespaceChecker::ST_ERROR) { ui->freeSpace->setText(""); } else { QString freeString = tr("%1 GB of free space available").arg(bytesAvailable / GB_BYTES); if (bytesAvailable < BLOCK_CHAIN_SIZE) { freeString += " " + tr("(of %1 GB needed)").arg(BLOCK_CHAIN_SIZE / GB_BYTES); ui->freeSpace->setStyleSheet("QLabel { color: #800000 }"); } else { ui->freeSpace->setStyleSheet(""); } ui->freeSpace->setText(freeString + "."); } /* Don't allow confirm in ERROR state */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR); } void Intro::on_dataDirectory_textChanged(const QString& dataDirStr) { /* Disable OK button until check result comes in */ ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); checkPath(dataDirStr); } void Intro::on_ellipsisButton_clicked() { QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, "Choose data directory", ui->dataDirectory->text())); if (!dir.isEmpty()) ui->dataDirectory->setText(dir); } void Intro::on_dataDirDefault_clicked() { setDataDirectory(getDefaultDataDirectory()); } void Intro::on_dataDirCustom_clicked() { ui->dataDirectory->setEnabled(true); ui->ellipsisButton->setEnabled(true); } void Intro::startThread() { thread = new QThread(this); FreespaceChecker* executor = new FreespaceChecker(this); executor->moveToThread(thread); connect(executor, SIGNAL(reply(int, QString, quint64)), this, SLOT(setStatus(int, QString, quint64))); connect(this, SIGNAL(requestCheck()), executor, SLOT(check())); /* make sure executor object is deleted in its own thread */ connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopThread()), thread, SLOT(quit())); thread->start(); } void Intro::checkPath(const QString& dataDir) { mutex.lock(); pathToCheck = dataDir; if (!signalled) { signalled = true; emit requestCheck(); } mutex.unlock(); } QString Intro::getPathToCheck() { QString retval; mutex.lock(); retval = pathToCheck; signalled = false; /* new request can be queued now */ mutex.unlock(); return retval; }
.include "defaults_mod.asm" table_file_jp equ "exe6-utf8.tbl" table_file_en equ "bn6-utf8.tbl" game_code_len equ 3 game_code equ 0x4252354A // BR5J game_code_2 equ 0x42523545 // BR5E game_code_3 equ 0x42523550 // BR5P card_type equ 1 card_id equ 6 card_no equ "006" card_sub equ "Mod Card 006" card_sub_x equ 64 card_desc_len equ 2 card_desc_1 equ "MetFire" card_desc_2 equ "20MB" card_desc_3 equ "" card_name_jp_full equ "メテファイア" card_name_jp_game equ "メテファイア" card_name_en_full equ "MetFire" card_name_en_game equ "MetFire" card_address equ "" card_address_id equ 0 card_bug equ 0 card_wrote_en equ "" card_wrote_jp equ ""
; A077163: n-th power of next n numbers. ; 1,4,9,64,125,216,2401,4096,6561,10000,161051,248832,371293,537824,759375,16777216,24137569,34012224,47045881,64000000,85766121,2494357888,3404825447,4586471424,6103515625,8031810176,10460353203 mov $2,7 lpb $2 add $0,1 mov $4,$0 add $5,1 lpb $4 mov $1,$0 pow $1,$5 bin $2,$3 trn $4,$5 add $5,1 lpe mul $1,10 lpe sub $1,10 div $1,10 add $1,1 mov $0,$1
; A169391: Number of reduced words of length n in Coxeter group on 42 generators S_i with relations (S_i)^2 = (S_i S_j)^31 = I. ; 1,42,1722,70602,2894682,118681962,4865960442,199504378122,8179679503002,335366859623082,13750041244546362,563751691026400842,23113819332082434522,947666592615379815402,38854330297230572431482 add $0,1 mov $3,1 lpb $0 sub $0,1 add $2,$3 div $3,$2 mul $2,41 lpe mov $0,$2 div $0,41
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1989 -- All Rights Reserved PROJECT: PC GEOS MODULE: Text/TextAttr FILE: taStyleDesc.asm AUTHOR: Tony ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 5/22/89 Initial revision DESCRIPTION: Routines for generating a text description of a style $Id: taStyleDesc.asm,v 1.1 97/04/07 11:18:50 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ TextStyleSheet segment resource COMMENT @---------------------------------------------------------------------- FUNCTION: DescribeTextStyle DESCRIPTION: Return a text description of a text style CALLED BY: INTERNAL PASS: es:di - buffer cx - bufer size left ds:si - style structure ds:dx - base style structure (dx = 0 for none) bp - number of characters already in buffer on stack - optr of extra UI to update RETURN: es:di - updated cx - updated DESTROYED: ax, bx, dx, si, ds REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/27/91 Initial version ------------------------------------------------------------------------------@ DescribeTextStyle proc far extraUI:optr, privateData:dword, attrsFlag:word ForceRef privateData .enter push cx, di movdw cxdi, extraUI call UpdateDescTextStyleAttributeList pop cx, di ; if we are describing attributes then we do not want to add these ; descriptions (because it does not make sense in the "Define New ; Style" dialog box. tst attrsFlag jnz done mov ax, ss:[bp] ;ax = # chars mov bx, handle TextStyleStrings mov dx, ds:[si].TSEH_privateData.TSPD_flags ; if there is anything here then add the string " + Character Only" test dx, mask TSF_APPLY_TO_SELECTION_ONLY jz afterCharOnly mov si, offset CharacterOnlyString call StyleSheetAddAttributeHeader mov ax, 1 afterCharOnly: test dx, mask TSF_POINT_SIZE_RELATIVE jz afterPS mov si, offset PointSizeRelativeString call StyleSheetAddAttributeHeader mov ax, 1 afterPS: test dx, mask TSF_MARGINS_RELATIVE jz afterMargins mov si, offset MarginsRelativeString call StyleSheetAddAttributeHeader mov ax, 1 afterMargins: test dx, mask TSF_LEADING_RELATIVE jz afterLeading mov si, offset LeadingRelativeString call StyleSheetAddAttributeHeader afterLeading: done: .leave ret @ArgSize DescribeTextStyle endp COMMENT @---------------------------------------------------------------------- FUNCTION: DescribeCharAttr DESCRIPTION: Return a text description of the differences between two char attr structures CALLED BY: INTERNAL PASS: es:di - buffer cx - bufer size left ds:si - derived attribute structure ds:dx - base attribute structure (dx = 0 for none) bp - number of characters already in buffer on stack - optr of extra UI to update RETURN: es:di - updated cx - updated DESTROYED: ax, bx, dx, si, ds REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/27/91 Initial version SH 05/06/94 XIP'ed ------------------------------------------------------------------------------@ DescribeCharAttr proc far extraUI:optr, privateData:dword, attrsFlag:word ForceRef extraUI ForceRef attrsFlag clr bx diffs local VisTextCharAttrDiffs \ push bx, bx, bx .enter ; call diff routine -- if no ruler passed then use default char attr ; and manually set the bits for the fields we always want to display push cx, dx, di, es segmov es, ds ;assume base structure passed mov di, dx tst dx jnz gotBaseCharAttr segmov es, cs mov di, offset defaultCharAttr FXIP< mov cx, size VisTextCharAttr > FXIP< call SysCopyToStackESDI ; es:di <- ptr to stack > mov diffs.VTCAD_diffs, mask VTCAF_MULTIPLE_FONT_IDS or \ mask VTCAF_MULTIPLE_POINT_SIZES FXIP< mov dx, ss > FXIP< lea bx, diffs ;dx:bx = diffs > FXIP< call DiffCharAttr > FXIP< call SysRemoveFromStack > FXIP< jmp xipDone > gotBaseCharAttr: mov dx, ss lea bx, diffs ;dx:bx = diffs call DiffCharAttr FXIP<xipDone: > andnf diffs.VTCAD_diffs, not mask VTCAF_MULTIPLE_STYLES andnf diffs.VTCAD_extendedStyles, not mask VTES_BACKGROUND_COLOR ; if there is anything here then add the string "Paragraph: " segmov es, ss lea di, diffs ;es:di = diffs clr ax mov cx, (size VisTextCharAttrDiffs) / 2 repe scasw pop cx, dx, di, es jz noDiffs push si mov ax, ss:[bp] mov bx, handle TextStyleStrings mov si, offset CharacterString call StyleSheetAddAttributeHeader pop si ; now go through the diff structure to generate text for all ; things that are different push bp mov bx, dx ;ds:bx = old structure mov dx, privateData.low mov ax, offset CADiffTable ;cs:ax = table pushdw csax mov ax, length CADiffTable ;ax = count lea bp, diffs call StyleSheetCallDescribeRoutines pop bp noDiffs: .leave ret @ArgSize DescribeCharAttr endp defaultCharAttr VisTextCharAttr < <<<1, 0>>, 0>, FID_DTC_URW_ROMAN, <0, 12>, <>, <C_BLACK, CF_INDEX, 0>, 0, FW_NORMAL, FWI_MEDIUM, <>, SDM_100, <>, <C_WHITE, CF_INDEX, 0>, SDM_0, <>, <> > NEW_CAT equ mask SSDF_NEW_CATEGORY CADiffTable SSDiffEntry \ <offset VTCAD_diffs, mask VTCAF_MULTIPLE_FONT_IDS, DescFont, 0>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_POINT_SIZES, DescPointSize, 0>, <offset VTCAD_textStyles, TextStyle, DescTextStyle, 0>, <offset VTCAD_extendedStyles, VisTextExtendedStyles, DescExtendedStyle, 0>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_COLORS, DescTextColor, NEW_CAT>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_GRAY_SCREENS, DescGrayScreen, 0>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_PATTERNS, DescPattern, 0>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_FONT_WEIGHTS, DescFontWeight, NEW_CAT>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_FONT_WIDTHS, DescFontWidth, NEW_CAT>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_TRACK_KERNINGS, DescTrackKerning, NEW_CAT>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_BG_COLORS, DescBGColor, NEW_CAT>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_BG_GRAY_SCREENS, DescBGGrayScreen, 0>, <offset VTCAD_diffs, mask VTCAF_MULTIPLE_BG_PATTERNS, DescBGPattern, 0> ; es:di = buffer, cx = count ; ds:si = new structure ; ds:bx = old structure ; ss:ax = diffs ; dx = TextStyleFlags ;--- DescFont proc far DBCS <fontName local FONT_NAME_LEN dup(wchar) > SBCS <fontName local FONT_NAME_LEN dup(char) > .enter mov ax, ds:[si].VTCA_fontID ;ax <- FontID push cx ;save buffer size mov cx, ax segmov ds, ss lea si, ss:fontName ;ds:si <- ptr to buffer call GrGetFontName jcxz unknownFont ;branch if font not found pop cx ;cx <- buffer size call StyleSheetAddNameFromPtr done: .leave ret ; ; Font is unknown, so display: ; Font=####, ; where #### is the font ID. ; unknownFont: pop cx ;cx <- buffer size mov si, offset UnknownFontString ;^lbx:si <- string call OurAddName ;add "Font=" call StyleSheetAddWord ;add "####" jmp done DescFont endp ;--- DescPointSize proc far clr ax clr bp test dx, mask TSF_POINT_SIZE_RELATIVE mov dx, ds:[si].VTCA_pointSize.WBF_int mov ah, ds:[si].VTCA_pointSize.WBF_frac jz notRelative tst bx jz notRelative sub ah, ds:[bx].VTCA_pointSize.WBF_frac sbb dx, ds:[bx].VTCA_pointSize.WBF_int mov bp, mask SSDDF_RELATIVE notRelative: ; dx.ah = value, convert to 13.3 shl ah rcl dx shl ah rcl dx shl ah rcl dx mov al, DU_POINTS clr bx call StyleSheetDescribeDistance ret DescPointSize endp ;--- DescTextStyle proc far mov_tr bp, ax clr ax mov al, ss:[bp].VTCAD_textStyles segmov ds, cs mov si, offset tsNameTable mov dx, length tsNameTable mov bx, handle TextStyleStrings call StyleSheetDescribeNonExclusiveWord ret DescTextStyle endp tsNameTable SSDescribeWordEntry \ <mask TS_UNDERLINE, offset UnderlineString>, <mask TS_OUTLINE, offset OutlineString>, <mask TS_BOLD, offset BoldString>, <mask TS_ITALIC, offset ItalicString>, <mask TS_STRIKE_THRU, offset StrikeThruString>, <mask TS_SUPERSCRIPT, offset SuperscriptString>, <mask TS_SUBSCRIPT, offset SubscriptString> ;--- DescExtendedStyle proc far mov_tr bp, ax mov ax, ss:[bp].VTCAD_extendedStyles segmov ds, cs mov si, offset etsNameTable mov dx, length etsNameTable mov bx, handle TextStyleStrings call StyleSheetDescribeNonExclusiveWord ret DescExtendedStyle endp etsNameTable SSDescribeWordEntry \ <mask VTES_BOXED, offset BoxedString>, <mask VTES_BUTTON, offset ButtonString>, <mask VTES_INDEX, offset IndexString>, <mask VTES_ALL_CAP, offset AllCapString>, <mask VTES_SMALL_CAP, offset SmallCapString>, <mask VTES_HIDDEN, offset HiddenString>, <mask VTES_CHANGE_BAR, offset ChangeBarString> ;--- DescFontWeight proc far clr dx mov dl, ds:[si].VTCA_fontWeight clr ax mov bx, handle FontWeightString mov si, offset FontWeightString call StyleSheetDescribeWWFixed ret DescFontWeight endp ;--- DescFontWidth proc far clr dx mov dl, ds:[si].VTCA_fontWidth clr ax mov bx, handle FontWidthString mov si, offset FontWidthString call StyleSheetDescribeWWFixed ret DescFontWidth endp ;--- DescTrackKerning proc far mov dx, ds:[si].VTCA_trackKerning clr ax mov bx, handle TrackKerningString mov si, offset TrackKerningString call StyleSheetDescribeWWFixed ret DescTrackKerning endp ;--- DescTextColor proc far clr bx add si, offset VTCA_color FALL_THRU DescColorCommon DescTextColor endp ; ds:si = SetColorParams, bx:dx = string DescColorCommon proc far ; for now just describe the standard colors clr ax mov al, ds:[si].CQ_redOrIndex mov si, dx tst bx jz 10$ call StyleSheetAddNameFromChunk call AddSpace 10$: segmov ds, cs mov si, offset colorTable mov dx, length colorTable mov bx, handle TextStyleStrings clr bp call StyleSheetDescribeExclusiveWord ret DescColorCommon endp colorTable SSDescribeWordEntry \ <C_BLACK, offset BlackString>, <C_BLUE, offset DarkBlueString>, <C_GREEN, offset DarkGreenString>, <C_CYAN, offset CyanString>, <C_RED, offset DarkRedString>, <C_VIOLET, offset DarkVioletString>, <C_BROWN, offset BrownString>, <C_LIGHT_GRAY, offset LightGrayString>, <C_DARK_GRAY, offset DarkGrayString>, <C_LIGHT_BLUE, offset LightBlueString>, <C_LIGHT_GREEN, offset LightGreenString>, <C_LIGHT_CYAN, offset LightCyanString>, <C_LIGHT_RED, offset LightRedString>, <C_LIGHT_VIOLET, offset LightVioletString>, <C_YELLOW, offset YellowString>, <C_WHITE, offset WhiteString> ;--- DescGrayScreen proc far mov dl, ds:[si].VTCA_grayScreen FALL_THRU DescGrayCommon DescGrayScreen endp ; dl = SystemDraskMask DescGrayCommon proc far mov si, offset FilledString cmp dl, SDM_100 jz gotString mov si, offset UnfilledString cmp dl, SDM_0 jz gotString clr dh ; dx = draw mask, get 64 - (dx - SDM_100) = -dx + (64+SDM_100) neg dx add dx, SDM_100 + 64 mov ax, (100*256)/64 mul dx ;dx.ax = result/128, use dl.ah adddw dxax, 0x80 ;round mov dh, dl mov dl, ah clr ax clr bx call StyleSheetDescribeWWFixed LocalLoadChar ax, '%' call StyleSheetAddCharToDescription call AddSpace mov si, offset HalftoneString gotString: call OurAddName ret DescGrayCommon endp ;--- DescPattern proc far mov ax, {word} ds:[si].VTCA_pattern FALL_THRU DescPatternCommon DescPattern endp ; ax = pattern (al = PatternType, ah = data) DescPatternCommon proc far segmov ds, cs mov si, offset patternTable mov dx, length patternTable mov bx, handle UnknownPatternString mov bp, offset UnknownPatternString call StyleSheetDescribeExclusiveWord call AddSpace mov si, offset PatternString GOTO OurAddName DescPatternCommon endp patternTable SSDescribeWordEntry \ <0, SolidPatternString>, <PT_SYSTEM_HATCH or (SH_VERTICAL shl 8), VerticalPatternString>, <PT_SYSTEM_HATCH or (SH_HORIZONTAL shl 8), HorizontalPatternString>, <PT_SYSTEM_HATCH or (SH_45_DEGREE shl 8), Degree45PatternString>, <PT_SYSTEM_HATCH or (SH_135_DEGREE shl 8), Degree135PatternString>, <PT_SYSTEM_HATCH or (SH_BRICK shl 8), BrickPatternString>, <PT_SYSTEM_HATCH or (SH_SLANTED_BRICK shl 8), SlantedBrickPatternString> ;--- DescBGColor proc far mov bx, handle BGColorString mov dx, offset BGColorString add si, offset VTCA_bgColor GOTO DescColorCommon DescBGColor endp ;--- DescBGGrayScreen proc far mov dl, ds:[si].VTCA_bgGrayScreen GOTO DescGrayCommon DescBGGrayScreen endp ;--- DescBGPattern proc far mov ax, {word} ds:[si].VTCA_bgPattern GOTO DescPatternCommon DescBGPattern endp ;========= AddSpace proc near push ax LocalLoadChar ax, ' ' call StyleSheetAddCharToDescription pop ax ret AddSpace endp COMMENT @---------------------------------------------------------------------- FUNCTION: DescribeParaAttr DESCRIPTION: Return a text description of the differences between two para attr structures CALLED BY: INTERNAL PASS: es:di - buffer cx - bufer size left ds:si - derived attribute structure ds:dx - base attribute structure (dx = 0 for none) bp - number of characters already in buffer on stack - optr of extra UI to update on stack - optr of extra UI to update RETURN: es:di - updated cx - updated DESTROYED: ax, bx, dx, si, bp, ds REGISTER/STACK USAGE: PSEUDO CODE/STRATEGY: KNOWN BUGS/SIDE EFFECTS/CAVEATS/IDEAS: REVISION HISTORY: Name Date Description ---- ---- ----------- Tony 12/27/91 Initial version ------------------------------------------------------------------------------@ DescribeParaAttr proc far extraUI:optr, privateData:dword, attrsFlag:word ForceRef extraUI ForceRef attrsFlag clr bx diffs local VisTextParaAttrDiffs \ push bx, bx, bx, bx, bx, bx, bx .enter ; call diff routine -- if no ruler passed then use default para attr ; and manually set the bits for the fields we always want to display push cx, dx, di, es segmov es, ds ;assume base structure passed mov di, dx tst dx jnz gotBaseParaAttr segmov es, cs mov di, offset defaultParaAttr FXIP< mov cx, size VisTextParaAttr > FXIP< call SysCopyToStackESDI ; es:di <- ptr to stack > mov diffs.VTPAD_attributes, mask VTPAA_JUSTIFICATION FXIP< mov dx, ss > FXIP< lea bx, diffs ;dx:bx = diffs > FXIP< call DiffParaAttr > FXIP< call SysRemoveFromStack > FXIP< jmp xipDone > gotBaseParaAttr: mov dx, ss lea bx, diffs ;dx:bx = diffs call DiffParaAttr FXIP<xipDone: > andnf diffs.VTPAD_diffs, not mask VTPAF_MULTIPLE_STYLES ; if there is anything here then add the string "Paragraph: " segmov es, ss lea di, diffs ;es:di = diffs clr ax mov cx, (size VisTextParaAttrDiffs) / 2 repe scasw pop cx, dx, di, es jz noDiffs push si mov ax, ss:[bp] mov bx, handle TextStyleStrings mov si, offset ParagraphString call StyleSheetAddAttributeHeader pop si ; now go through the diff structure to generate text for all ; things that are different push bp mov bx, dx ;ds:bx = old structure mov dx, privateData.low mov ax, offset PADiffTable ;cs:ax = table pushdw csax mov ax, length PADiffTable ;ax = count lea bp, diffs call StyleSheetCallDescribeRoutines pop bp noDiffs: .leave ret @ArgSize DescribeParaAttr endp defaultParaAttr VisTextParaAttr < <<<1, 0>>, CA_NULL_ELEMENT>, <0, 0, 0, 0, 0, 0, SA_TOP_LEFT>, <C_BLACK, CF_INDEX, 0>, <0, 0, 0, 0, 0, 0, 0, 0, 0>, ;attributes 0*PIXELS_PER_INCH, 0*PIXELS_PER_INCH, 0*PIXELS_PER_INCH, ;margins <0, 1>, 0, 0, 0, <C_WHITE, CF_INDEX, 0>, ;bg color 0, 1*8, 2*8, 1*8, SDM_100, SDM_0, <>, <>, (PIXELS_PER_INCH*8)/2, VIS_TEXT_DEFAULT_STARTING_NUMBER, <0,0,0,0>, <>, <>, <>, <> > PADiffTable SSDiffEntry \ <offset VTPAD_attributes, mask VTPAA_JUSTIFICATION, DescJustification, 0>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_LEFT_MARGINS, DescLeftMargin, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_PARA_MARGINS, DescParaMargin, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_RIGHT_MARGINS, DescRightMargin, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_LINE_SPACINGS or mask VTPAF_MULTIPLE_LEADINGS, DescLineSpacingAndLeading, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_TOP_SPACING, DescTopSpacing, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_BOTTOM_SPACING, DescBottomSpacing, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_DEFAULT_TABS, DescDefaultTabs, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_BG_COLORS, DescParaBGColor, NEW_CAT>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_BG_GRAY_SCREENS, DescParaBGGrayScreen, 0>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_BG_PATTERNS, DescParaBGPattern, 0>, <offset VTPAD_diffs, mask VTPAF_MULTIPLE_TAB_LISTS, DescTabList, NEW_CAT>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_LEFT or \ mask VTPABF_MULTIPLE_BORDER_TOP or \ mask VTPABF_MULTIPLE_BORDER_RIGHT or \ mask VTPABF_MULTIPLE_BORDER_BOTTOM or \ mask VTPABF_MULTIPLE_BORDER_DOUBLES or \ mask VTPABF_MULTIPLE_BORDER_DRAW_INNERS or \ mask VTPABF_MULTIPLE_BORDER_ANCHORS or \ mask VTPABF_MULTIPLE_BORDER_SHADOWS, DescBorder, NEW_CAT>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_WIDTHS, DescBorderWidth, NEW_CAT>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_SPACINGS, DescBorderSpacing, NEW_CAT>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_COLORS, DescBorderColor, NEW_CAT>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_GRAY_SCREENS, DescBorderGrayScreen, 0>, <offset VTPAD_borderDiffs, mask VTPABF_MULTIPLE_BORDER_PATTERNS, DescBorderPattern, 0>, <offset VTPAD_attributes, mask VTPAA_DISABLE_WORD_WRAP, DescDisableWordWrap, NEW_CAT>, <offset VTPAD_attributes, mask VTPAA_COLUMN_BREAK_BEFORE, DescColumnBreakBefore, NEW_CAT>, <offset VTPAD_attributes, mask VTPAA_KEEP_PARA_WITH_NEXT, DescKeepParaWithNext, NEW_CAT>, <offset VTPAD_attributes, mask VTPAA_KEEP_PARA_TOGETHER, DescKeepParaTogether, NEW_CAT>, <offset VTPAD_attributes, mask VTPAA_ALLOW_AUTO_HYPHENATION, DescAutoHyphenation, NEW_CAT>, <offset VTPAD_hyphenationInfo, mask VTHI_HYPHEN_MAX_LINES, DescHyphenationMaxLines, NEW_CAT>, <offset VTPAD_hyphenationInfo, mask VTHI_HYPHEN_SHORTEST_WORD, DescHyphenationShortestWord, NEW_CAT>, <offset VTPAD_hyphenationInfo, mask VTHI_HYPHEN_SHORTEST_PREFIX, DescHyphenationShortestPrefix, NEW_CAT>, <offset VTPAD_hyphenationInfo, mask VTHI_HYPHEN_SHORTEST_SUFFIX, DescHyphenationShortestSuffix, NEW_CAT>, <offset VTPAD_attributes, mask VTPAA_KEEP_LINES, DescKeepLines, NEW_CAT>, <offset VTPAD_keepInfo, mask VTKI_TOP_LINES, DescKeepTop, NEW_CAT>, <offset VTPAD_keepInfo, mask VTKI_BOTTOM_LINES, DescKeepBottom, NEW_CAT> ;--- DescJustification proc far mov ax, ds:[si].VTPA_attributes if CHAR_JUSTIFICATION .assert (offset VTPAA_JUSTIFICATION gt 8) ornf al, ds:[si].VTPA_miscMode and ax, mask VTPAA_JUSTIFICATION or mask TMMF_CHARACTER_JUSTIFICATION else and ax, mask VTPAA_JUSTIFICATION endif segmov ds, cs mov si, offset justNameTable mov dx, length justNameTable mov bx, handle TextStyleStrings call StyleSheetDescribeExclusiveWord ret DescJustification endp if CHAR_JUSTIFICATION justNameTable SSDescribeWordEntry \ <J_LEFT shl offset VTPAA_JUSTIFICATION, offset LeftJustString>, <J_CENTER shl offset VTPAA_JUSTIFICATION, offset CenterJustString>, <J_RIGHT shl offset VTPAA_JUSTIFICATION, offset RightJustString>, <J_FULL shl offset VTPAA_JUSTIFICATION, offset FullJustString>, <J_FULL shl offset VTPAA_JUSTIFICATION or mask TMMF_CHARACTER_JUSTIFICATION, offset FullCharJustString> else justNameTable SSDescribeWordEntry \ <J_LEFT shl offset VTPAA_JUSTIFICATION, offset LeftJustString>, <J_CENTER shl offset VTPAA_JUSTIFICATION, offset CenterJustString>, <J_RIGHT shl offset VTPAA_JUSTIFICATION, offset RightJustString>, <J_FULL shl offset VTPAA_JUSTIFICATION, offset FullJustString> endif ;--- DescLeftMargin proc far mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED test dx, mask TSF_MARGINS_RELATIVE mov dx, ds:[si].VTPA_leftMargin jz notRelative tst bx jz notRelative sub dx, ds:[bx].VTPA_leftMargin mov bp, mask SSDDF_RELATIVE notRelative: mov al, DU_INCHES_OR_CENTIMETERS mov bx, handle LeftMarginString mov si, offset LeftMarginString call StyleSheetDescribeDistance ret DescLeftMargin endp ;--- DescParaMargin proc far mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED test dx, mask TSF_MARGINS_RELATIVE mov dx, ds:[si].VTPA_paraMargin jz notRelative tst bx jz notRelative sub dx, ds:[bx].VTPA_paraMargin mov bp, mask SSDDF_RELATIVE notRelative: mov al, DU_INCHES_OR_CENTIMETERS mov bx, handle ParaMarginString mov si, offset ParaMarginString call StyleSheetDescribeDistance ret DescParaMargin endp ;--- DescRightMargin proc far mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED test dx, mask TSF_MARGINS_RELATIVE mov dx, ds:[si].VTPA_rightMargin jz notRelative tst bx jz notRelative sub dx, ds:[bx].VTPA_rightMargin mov bp, mask SSDDF_RELATIVE notRelative: mov al, DU_INCHES_OR_CENTIMETERS mov bx, handle RightMarginString mov si, offset RightMarginString call StyleSheetDescribeDistance ret DescRightMargin endp ;--- DescLineSpacingAndLeading proc far tst ds:[si].VTPA_leading jnz leading ; describe line spacing only clrdw dxax mov dl, ds:[si].VTPA_lineSpacing.high mov ah, ds:[si].VTPA_lineSpacing.low mov bx, handle LineSpacingString mov si, offset LineSpacingString call StyleSheetDescribeWWFixed ret leading: ; describe leading only mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED test dx, mask TSF_LEADING_RELATIVE mov dx, ds:[si].VTPA_leading jz notRelative tst bx jz notRelative sub ax, ds:[bx].VTPA_leading mov bp, mask SSDDF_RELATIVE notRelative: mov al, DU_POINTS_OR_MILLIMETERS mov bx, handle LeadingString mov si, offset LeadingString call StyleSheetDescribeDistance ret DescLineSpacingAndLeading endp ;--- DescTopSpacing proc far mov dx, ds:[si].VTPA_spaceOnTop mov al, DU_POINTS_OR_MILLIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov bx, handle TopSpacingString mov si, offset TopSpacingString call StyleSheetDescribeDistance ret DescTopSpacing endp ;--- DescBottomSpacing proc far mov dx, ds:[si].VTPA_spaceOnBottom mov al, DU_POINTS_OR_MILLIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov bx, handle BottomSpacingString mov si, offset BottomSpacingString call StyleSheetDescribeDistance ret DescBottomSpacing endp ;--- DescDefaultTabs proc far mov dx, ds:[si].VTPA_defaultTabs tst dx jz none mov al, DU_INCHES_OR_CENTIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov bx, handle DefaultTabsString mov si, offset DefaultTabsString call StyleSheetDescribeDistance ret none: mov si, offset NoDefaultTabsString FALL_THRU OurAddName DescDefaultTabs endp OurAddName proc far mov bx, handle NoDefaultTabsString call StyleSheetAddNameFromChunk ret OurAddName endp ;--- DescParaBGColor proc far mov bx, handle ParaBGColorString mov dx, offset ParaBGColorString add si, offset VTPA_bgColor GOTO DescColorCommon DescParaBGColor endp ;--- DescParaBGGrayScreen proc far mov dl, ds:[si].VTPA_bgGrayScreen GOTO DescGrayCommon DescParaBGGrayScreen endp ;--- DescParaBGPattern proc far mov ax, {word} ds:[si].VTPA_bgPattern GOTO DescPatternCommon DescParaBGPattern endp ;--- ; Tabs: 1 inch, 2 inches centered, ; 3 inches anchored with '.' with bullet leader ; 50% halftone 3 point wide lines 4 point spacing, ; 4 inches anchored 50% halftone DescTabList proc far clr ax mov al, ds:[si].VTPA_numberOfTabs tst ax jnz haveTabs mov si, offset NoTabsString GOTO OurAddName haveTabs: lea bp, ds:[si].VTPA_tabList mov si, offset TabsString call OurAddName call AddSpace tabLoop: push ax push bp mov dx, ds:[bp].T_position mov al, DU_INCHES_OR_CENTIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED clr bx call StyleSheetDescribeDistance pop bp clr ax mov al, ds:[bp].T_attr push ax and al, mask TA_TYPE cmp al, TT_LEFT jz afterType call AddSpace push ds segmov ds, cs mov bx, handle TabsString mov si, offset tabTypesTable mov dx, length tabTypesTable call StyleSheetDescribeExclusiveWord pop ds cmp al, TT_ANCHORED jnz afterType call AddSpace mov si, offset AnchoredWithString call OurAddName mov al, ds:[bp].T_anchor.low call StyleSheetAddCharToDescription mov si, offset AnchoredEndString call OurAddName afterType: pop ax and al, mask TA_LEADER jz afterLeader call AddSpace mov si, offset WithString call OurAddName call AddSpace push ds segmov ds, cs mov si, offset tabLeadersTable mov dx, length tabLeadersTable call StyleSheetDescribeExclusiveWord pop ds call AddSpace mov si, offset LeaderString call OurAddName afterLeader: mov dl, ds:[bp].T_grayScreen cmp dl, SDM_100 jz afterGray call AddSpace call DescGrayCommon afterGray: clr dx mov dl, ds:[bp].T_lineWidth tst dx jz afterLineWidth push bp call AddSpace mov al, DU_POINTS_OR_MILLIMETERS clr bp clr bx call StyleSheetDescribeDistance mov bx, handle TabLineWidthString mov si, offset TabLineWidthString call AddSpace call OurAddName pop bp afterLineWidth: clr dx mov dl, ds:[bp].T_lineSpacing cmp dx, 1*8 jz afterLineSpacing push bp call AddSpace mov al, DU_POINTS_OR_MILLIMETERS clr bp clr bx call StyleSheetDescribeDistance mov bx, handle TabLineSpacingString mov si, offset TabLineSpacingString call AddSpace call OurAddName pop bp afterLineSpacing: add bp, size Tab pop ax dec ax jz done push ax LocalLoadChar ax, ',' call StyleSheetAddCharToDescription pop ax call AddSpace jmp tabLoop done: ret DescTabList endp tabTypesTable SSDescribeWordEntry \ <TT_CENTER, offset CenterJustString>, <TT_RIGHT, offset RightJustString>, <TT_ANCHORED, offset AnchoredString> tabLeadersTable SSDescribeWordEntry \ <TL_DOT shl offset TA_LEADER, offset DotLeaderString>, <TL_LINE shl offset TA_LEADER, offset LineLeaderString>, <TL_BULLET shl offset TA_LEADER, offset BulletLeaderString> ;--- ; "Double Line Border" DescBorder proc far mov ax, ds:[si].VTPA_borderFlags clr dx mov dl, ds:[si].VTPA_borderShadow test ax, mask VTPBF_LEFT or mask VTPBF_TOP or mask VTPBF_RIGHT \ or mask VTPBF_BOTTOM jnz borderExists mov si, offset NoBorderString GOTO OurAddName borderExists: ; first output the border type mov si, offset DoubleBorderString test ax, mask VTPBF_DOUBLE jnz gotType mov si, offset ShadowBorderString test ax, mask VTPBF_SHADOW jnz gotType mov si, offset NormalBorderString gotType: call OurAddName ;sets bx push ax test ax, mask VTPBF_DOUBLE jz notDouble ; "Double Line Border" ; "Double Line Border with 2 points between lines" cmp dx, 1*8 jz afterDoubleWidth mov al, DU_POINTS_OR_MILLIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov si, offset WithString call AddSpace call StyleSheetDescribeDistance mov si, offset SpaceBetweenString call AddSpace call OurAddName afterDoubleWidth: jmp common notDouble: test ax, mask VTPBF_SHADOW jz common ; "Shadowed Border" ; "Shadowed Border from bottom-right" ; "Shadowed Border with 2 point shadow" ; "Shadowed Border from bottom-right with 2 point shadow" and ax, mask VTPBF_ANCHOR CheckHack <SA_TOP_LEFT eq 0> jz afterShadow mov si, offset ShadowTopRightString CheckHack <SA_TOP_RIGHT eq 1> dec ax jz gotShadow mov si, offset ShadowBottomLeftString CheckHack <SA_BOTTOM_LEFT eq 2> dec ax jz gotShadow mov si, offset ShadowBottomRightString CheckHack <SA_BOTTOM_RIGHT eq 3> gotShadow: call AddSpace call OurAddName afterShadow: cmp dx, 1*8 jz afterShadowWidth mov al, DU_POINTS_OR_MILLIMETERS clr bp mov si, offset WithString call AddSpace call StyleSheetDescribeDistance mov si, offset ShadowWidthString call AddSpace call OurAddName afterShadowWidth: ;----- common: pop ax ; "Normal Border top,left sides only" push ax and ax, mask VTPBF_LEFT or mask VTPBF_TOP or mask VTPBF_RIGHT \ or mask VTPBF_BOTTOM cmp ax, mask VTPBF_LEFT or mask VTPBF_TOP or mask VTPBF_RIGHT \ or mask VTPBF_BOTTOM jz afterSides call AddSpace segmov ds, cs mov si, offset sidesTable mov dx, length sidesTable call StyleSheetDescribeNonExclusiveWord mov si, offset SideString cmp ax, 1 jz gotSideString mov si, offset SidesString gotSideString: call AddSpace call OurAddName afterSides: pop ax test ax, mask VTPBF_DRAW_INNER_LINES jz afterInner mov si, offset DrawInnerString LocalLoadChar ax, ',' call StyleSheetAddCharToDescription call AddSpace call OurAddName afterInner: ret DescBorder endp sidesTable SSDescribeWordEntry \ <mask VTPBF_LEFT, offset LeftString>, <mask VTPBF_TOP, offset TopString>, <mask VTPBF_RIGHT, offset RightString>, <mask VTPBF_BOTTOM, offset BottomString> ;--- DescBorderWidth proc far clr dx mov dl, ds:[si].VTPA_borderWidth mov al, DU_POINTS_OR_MILLIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov bx, handle BorderWidthString mov si, offset BorderWidthString call StyleSheetDescribeDistance ret DescBorderWidth endp ;--- DescBorderSpacing proc far clr dx mov dl, ds:[si].VTPA_borderSpacing mov al, DU_POINTS_OR_MILLIMETERS mov bp, mask SSDDF_PLURAL_FOR_NON_RELATIVE_IF_NEEDED mov bx, handle BorderSpacingString mov si, offset BorderSpacingString call StyleSheetDescribeDistance ret DescBorderSpacing endp ;--- DescBorderColor proc far mov bx, handle BorderColorString mov dx, offset BorderColorString add si, offset VTPA_borderColor GOTO DescColorCommon DescBorderColor endp ;--- DescBorderGrayScreen proc far mov dl, ds:[si].VTPA_borderGrayScreen GOTO DescGrayCommon DescBorderGrayScreen endp ;--- DescBorderPattern proc far mov ax, {word} ds:[si].VTPA_borderPattern GOTO DescPatternCommon DescBorderPattern endp ;--- DescDisableWordWrap proc far mov si, offset DisableWordWrapString GOTO OurAddName DescDisableWordWrap endp ;--- DescColumnBreakBefore proc far mov si, offset ColumnBreakBeforeString GOTO OurAddName DescColumnBreakBefore endp ;--- DescKeepParaWithNext proc far mov si, offset KeepParaWithNextString GOTO OurAddName DescKeepParaWithNext endp ;--- DescKeepParaTogether proc far mov si, offset KeepParaTogetherString GOTO OurAddName DescKeepParaTogether endp ;--- DescAutoHyphenation proc far mov si, offset AutoHyphenationString GOTO OurAddName DescAutoHyphenation endp ;--- DescHyphenationMaxLines proc far mov dx, ds:[si].VTPA_hyphenationInfo mov si, offset MaxLinesString and dx, mask VTHI_HYPHEN_MAX_LINES mov al, offset VTHI_HYPHEN_MAX_LINES FALL_THRU HyphenCommon DescHyphenationMaxLines endp HyphenCommon proc far mov bp, 1 FALL_THRU DescFieldCommon HyphenCommon endp DescFieldCommon proc far xchg ax, cx shr dx, cl mov_tr cx, ax add dx, bp ;dx.cx = value clr ax clr bp mov bx, handle TextStyleStrings call StyleSheetDescribeWWFixed ret DescFieldCommon endp ;--- DescHyphenationShortestWord proc far mov dx, ds:[si].VTPA_hyphenationInfo mov si, offset ShortestWordString and dx, mask VTHI_HYPHEN_SHORTEST_WORD mov al, offset VTHI_HYPHEN_SHORTEST_WORD GOTO HyphenCommon DescHyphenationShortestWord endp ;--- DescHyphenationShortestPrefix proc far mov dx, ds:[si].VTPA_hyphenationInfo mov si, offset ShortestPrefixString and dx, mask VTHI_HYPHEN_SHORTEST_PREFIX mov al, offset VTHI_HYPHEN_SHORTEST_PREFIX GOTO HyphenCommon DescHyphenationShortestPrefix endp ;--- DescHyphenationShortestSuffix proc far mov dx, ds:[si].VTPA_hyphenationInfo mov si, offset ShortestSuffixString and dx, mask VTHI_HYPHEN_SHORTEST_SUFFIX mov al, offset VTHI_HYPHEN_SHORTEST_SUFFIX GOTO HyphenCommon DescHyphenationShortestSuffix endp ;--- DescKeepLines proc far mov si, offset KeepLinesString GOTO OurAddName DescKeepLines endp ;--- DescKeepTop proc far mov dl, ds:[si].VTPA_keepInfo mov si, offset KeepTopString and dx, mask VTKI_TOP_LINES mov al, offset VTKI_TOP_LINES FALL_THRU KeepCommon DescKeepTop endp KeepCommon proc far mov bp, 2 GOTO DescFieldCommon KeepCommon endp ;--- DescKeepBottom proc far mov dl, ds:[si].VTPA_keepInfo mov si, offset KeepBottomString and dx, mask VTKI_BOTTOM_LINES mov al, offset VTKI_BOTTOM_LINES GOTO KeepCommon DescKeepBottom endp TextStyleSheet ends
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtCore/QJsonDocument> #include <QtCore/QTimer> #include <QtRestClient/RestReply> #include <QtRestClient/RestClass> using namespace QtRestClient; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow), client(new RestClient(this)) { ui->setupUi(this); client->setBaseUrl(QStringLiteral("http://api.example.com")); connect(client->manager(), &QNetworkAccessManager::authenticationRequired, this, &MainWindow::authenticate); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_addParamButton_clicked() { auto item = new QTreeWidgetItem(ui->paramTreeWidget); item->setFlags(item->flags() | Qt::ItemIsEditable); ui->paramTreeWidget->setCurrentItem(item); ui->paramTreeWidget->editItem(item); } void MainWindow::on_removeParamButton_clicked() { auto current = ui->paramTreeWidget->currentItem(); if(current) delete current; } void MainWindow::on_addHeaderButton_clicked() { auto item = new QTreeWidgetItem(ui->headersTreeWidget); item->setFlags(item->flags() | Qt::ItemIsEditable); ui->headersTreeWidget->setCurrentItem(item); ui->headersTreeWidget->editItem(item); } void MainWindow::on_removeHeaderButton_clicked() { auto current = ui->headersTreeWidget->currentItem(); if(current) delete current; } void MainWindow::on_pushButton_clicked() { ui->tabWidget->setCurrentWidget(ui->replyTab); QVariantHash params; for(auto i = 0; i < ui->paramTreeWidget->topLevelItemCount(); i++) { auto item = ui->paramTreeWidget->topLevelItem(i); params.insert(item->text(0), item->text(1)); } HeaderHash headers; for(auto i = 0; i < ui->headersTreeWidget->topLevelItemCount(); i++) { auto item = ui->headersTreeWidget->topLevelItem(i); headers.insert(item->text(0).toUtf8(), item->text(1).toUtf8()); } QJsonParseError error; QJsonDocument body; if(!ui->bodyJsonEdit->toPlainText().isEmpty()) body = QJsonDocument::fromJson(ui->bodyJsonEdit->toPlainText().toUtf8(), &error); else error.error = QJsonParseError::NoError; RestReply *reply; if(error.error != QJsonParseError::NoError) { ui->codeLineEdit->setText(QString::number(error.error)); ui->networkErrorLineEdit->setText(error.errorString()); ui->replyJsonEdit->clear(); return; } else if(body.isObject()) { reply = client->rootClass()->callJson(ui->verbComboBox->currentText().toUtf8(), QUrl(ui->urlLineEdit->text()), body.object(), params, headers); } else if(body.isArray()) { reply = client->rootClass()->callJson(ui->verbComboBox->currentText().toUtf8(), QUrl(ui->urlLineEdit->text()), body.array(), params, headers); } else { reply = client->rootClass()->callJson(ui->verbComboBox->currentText().toUtf8(), QUrl(ui->urlLineEdit->text()), params, headers); } connect(reply, &RestReply::succeeded, this, [=](int status, QJsonValue value){ ui->codeLineEdit->setText(QString::number(status)); ui->networkErrorLineEdit->clear(); QJsonDocument doc; if(value.isObject()) doc = QJsonDocument(value.toObject()); else doc = QJsonDocument(value.toArray()); ui->replyJsonEdit->setPlainText(QString::fromUtf8(doc.toJson(QJsonDocument::Indented))); QTimer::singleShot(2000, this, &MainWindow::zeroBars); }); connect(reply, &RestReply::failed, this, [=](int status, QJsonValue value){ ui->codeLineEdit->setText(QString::number(status)); ui->networkErrorLabel->setText(tr("Request failure:")); ui->networkErrorLineEdit->setText(tr("Request Failed! See JSON for more details!")); QJsonDocument doc; if(value.isObject()) doc = QJsonDocument(value.toObject()); else doc = QJsonDocument(value.toArray()); ui->replyJsonEdit->setPlainText(QString::fromUtf8(doc.toJson(QJsonDocument::Indented))); QTimer::singleShot(2000, this, &MainWindow::zeroBars); }); connect(reply, &RestReply::error, this, [=](QString errorString, int code, RestReply::ErrorType type){ ui->codeLineEdit->setText(QString::number(code)); ui->networkErrorLabel->setText(type == RestReply::NetworkError ? tr("Network error:") : tr("JSON parse error:")); ui->networkErrorLineEdit->setText(errorString); ui->replyJsonEdit->clear(); QTimer::singleShot(2000, this, &MainWindow::zeroBars); }); ui->requestUrlLineEdit->setText(reply->networkReply()->url().toString()); connect(reply, &RestReply::uploadProgress, this, [this](int c, int m){ ui->uploadBar->setMaximum(m); ui->uploadBar->setValue(c); }); connect(reply, &RestReply::downloadProgress, this, [this](int c, int m){ ui->downloadBar->setMaximum(m); ui->downloadBar->setValue(c); }); } void MainWindow::authenticate(QNetworkReply *, QAuthenticator *auth) { auth->setUser(ui->usernameLineEdit->text()); auth->setPassword(ui->passwordLineEdit->text()); } void MainWindow::zeroBars() { ui->uploadBar->setMaximum(100); ui->uploadBar->setValue(0); ui->downloadBar->setMaximum(100); ui->downloadBar->setValue(0); }
ORG $8000 PUBLIC HIGHPAGEADDR, SIO_INT, SIO_RCVBUF, SIO_CNT, SIO_RTS, ORG_H_KEYI include "sio.inc" HIGHPAGEADDR: EQU $ SIO_RCVBUF: SIO_CNT: DB 0 ; CHARACTERS IN RING BUFFER SIO_HD: DW SIO_BUF ; BUFFER HEAD POINTER SIO_TL: DW SIO_BUF ; BUFFER TAIL POINTER SIO_BUF: DS SIO_BUFSZ, $00 ; RECEIVE RING BUFFER SIO_RTS: DB $FF ; 0 => RTS OFF, $FF => RTS ON ORG_H_KEYI: DS 5, 0 SIO_INT: DI ; INTERRUPTS WILL BE RE-ENABLED BY MSX BIOS ; CHECK TO SEE IF SOMETHING IS ACTUALLY THERE XOR A ; READ REGISTER 0 OUT (CMD_CH), A IN A, (CMD_CH) AND $01 ; ISOLATE RECEIVE READY BIT RET Z ; NOTHING AVAILABLE ON CURRENT CHANNEL SIO_INTRCV1: ; RECEIVE CHARACTER INTO BUFFER IN A, (DAT_CH) ; READ PORT LD B, A ; SAVE BYTE READ LD HL, SIO_RCVBUF LD A, (HL) ; GET COUNT CP SIO_BUFSZ ; COMPARE TO BUFFER SIZE JR Z, SIO_INTRCV4 ; BAIL OUT IF BUFFER FULL, RCV BYTE DISCARDED INC A ; INCREMENT THE COUNT LD (HL), A ; AND SAVE IT CP SIO_BUF_HI ; BUFFER GETTING FULL? JR NZ, SIO_INTRCV2 ; IF NOT, BYPASS CLEARING RTS LD A, 5 ; SELECTED REGISTER WRITE 5 OUT (CMD_CH), A LD A, SIO_RTSOFF OUT (CMD_CH), A XOR A LD (SIO_RTS), A SIO_INTRCV2: INC HL ; HL NOW HAS ADR OF HEAD PTR PUSH HL ; SAVE ADR OF HEAD PTR LD A, (HL) ; DEREFERENCE HL INC HL LD H, (HL) LD L, A ; HL IS NOW ACTUAL HEAD PTR LD (HL), B ; SAVE CHARACTER RECEIVED IN BUFFER AT HEAD INC HL ; BUMP HEAD POINTER POP DE ; RECOVER ADR OF HEAD PTR LD A, L ; GET LOW BYTE OF HEAD PTR SUB SIO_BUFSZ+4 ; SUBTRACT SIZE OF BUFFER AND POINTER CP E ; IF EQUAL TO START, HEAD PTR IS PAST BUF END JR NZ, SIO_INTRCV3 ; IF NOT, BYPASS LD H, D ; SET HL TO LD L, E ; ... HEAD PTR ADR INC HL ; BUMP PAST HEAD PTR INC HL INC HL INC HL ; ... SO HL NOW HAS ADR OF ACTUAL BUFFER START SIO_INTRCV3: EX DE, HL ; DE := HEAD PTR VAL, HL := ADR OF HEAD PTR LD (HL), E ; SAVE UPDATED HEAD PTR INC HL LD (HL), D ; CHECK FOR MORE PENDING... XOR A OUT (CMD_CH), A ; READ REGISTER 0 IN A, (CMD_CH) ; RRA ; READY BIT TO CF JR C, SIO_INTRCV1 ; IF SET, DO SOME MORE LD A, (SIO_RTS) OR A JR Z, SIO_INTRCV4 ; ABORT NOW IF RTS IS OFF ; TEST FOR NEW BYTES FOR A SHORT PERIOD OF TIME LD B, 40 SIO_MORE: IN A, (CMD_CH) ; RRA ; READY BIT TO CF JR C, SIO_INTRCV1 ; IF SET, DO SOME MORE DJNZ SIO_MORE SIO_INTRCV4: ; RESET INTERRUPT STATE IN SIO (CHANNEL A CONTROLS CHANNEL B ALSO) LD A, 0 OUT (SIO0A_CMD), A LD A, $38 OUT (SIO0A_CMD), A RET
; ; char *asm_strncpy(char *dest, char *src, size_t num); ; BITS 64 SECTION .text GLOBAL asm_strncpy asm_strncpy: PUSH RCX MOV RCX, -1 _loop: INC RCX CMP RCX, RDX JGE _end MOV AL, BYTE [RSI + RCX] MOV BYTE [RDI + RCX], AL CMP BYTE [RSI + RCX], 0 JNE _loop _end: MOV RAX, RDI POP RCX RET
//****************************************************************************************************** //**** PROJECT HEADER FILES //****************************************************************************************************** #include "Cursors.h" //****************************************************************************************************** //**** CONSTANT DEFINITIONS //****************************************************************************************************** uint8 c_v_resize_cursor_data[68] = { 16, 1, 7, 7, 0, 0, //0000000000000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 17, 16, //0001000100010000 49, 24, //0011000100011000 113, 28, //0111000100011100 49, 24, //0011000100011000 17, 16, //0001000100010000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 0, 0, //0000000000000000 0, 0, //0000000000000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 27, 176, //0001101110110000 59, 184, //0011101110111000 123, 188, //0111101110111100 251, 190, //1111101110111110 123, 188, //0111101110111100 59, 184, //0011101110111000 27, 176, //0001101110110000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 0, 0 //0000000000000000 }; uint8 c_h_resize_cursor_data[68] = { 16, 1, 7, 7, 0, 0, //0000000000000000 1, 0, //0000000100000000 3, 128, //0000001110000000 7, 192, //0000011111000000 0, 0, //0000000000000000 0, 0, //0000000000000000 0, 0, //0000000000000000 127, 252, //0111111111111100 0, 0, //0000000000000000 0, 0, //0000000000000000 0, 0, //0000000000000000 7, 192, //0000011111000000 3, 128, //0000001110000000 1, 0, //0000000100000000 0, 0, //0000000000000000 0, 0, //0000000000000000 1, 0, //0000000100000000 3, 128, //0000001110000000 7, 192, //0000011111000000 15, 224, //0000111111100000 15, 224, //0000111111100000 0, 0, //0000000000000000 255, 254, //1111111111111110 255, 254, //1111111111111110 255, 254, //1111111111111110 0, 0, //0000000000000000 15, 224, //0000111111100000 15, 224, //0000111111100000 7, 192, //0000011111000000 3, 128, //0000001110000000 1, 0, //0000000100000000 0, 0 //0000000000000000 }; uint8 c_crosshairs_cursor_data[68] = { 16, 1, 7, 7, 0, 0, //0000000000000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 0, 0, //0000000000000000 125, 124, //0111110101111100 0, 0, //0000000000000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 1, 0, //0000000100000000 0, 0, //0000000000000000 0, 0, //0000000000000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 255, 254, //1111111111111110 255, 254, //1111111111111110 255, 254, //1111111111111110 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 3, 128, //0000001110000000 0, 0 //0000000000000000 }; uint8 c_magnify_cursor_data[68] = { 16, 1, 6, 6, 0, 0, //0000000000000000 7, 0, //0000011100000000 24, 192, //0001100011000000 32, 32, //0010000000100000 32, 32, //0010000000100000 64, 16, //0100000000010000 64, 16, //0100000000010000 64, 16, //0100000000010000 32, 32, //0010000000100000 32, 32, //0010000000100000 24, 240, //0001100011110000 7, 56, //0000011100111000 0, 28, //0000000000011100 0, 14, //0000000000001110 0, 4, //0000000000000100 0, 0, //0000000000000000 7, 0, //0000011100000000 31, 192, //0001111111000000 63, 224, //0011111111100000 120, 240, //0111100011110000 112, 112, //0111000001110000 224, 56, //1110000000111000 224, 56, //1110000000111000 224, 56, //1110000000111000 112, 112, //0111000001110000 120, 240, //0111100011110000 63, 248, //0011111111111000 31, 252, //0001111111111100 7, 62, //0000011100111110 0, 31, //0000000000011111 0, 14, //0000000000001110 0, 4, //0000000000000100 }; const void* c_v_resize_cursor = c_v_resize_cursor_data; const void* c_h_resize_cursor = c_h_resize_cursor_data; const void* c_crosshairs_cursor = c_crosshairs_cursor_data; const void* c_magnify_cursor = c_magnify_cursor_data;
; A114003: Rows sums of triangle A114002. ; 1,3,3,5,3,7,3,7,5,7,3,11,3,7,7,9,3,11,3,11,7,7,3,15,5,7,7,11,3,15,3,11,7,7,7,17,3,7,7,15,3,15,3,11,11,7,3,19,5,11,7,11,3,15,7,15,7,7,3,23,3,7,11,13,7,15,3,11,7,15,3,23,3,7,11,11,7,15,3,19,9,7,3,23,7,7,7,15,3,23,7,11,7,7,7,23,3,11,11,17,3,15,3,15,15,7,3,23,3,15,7,19,3,15,7,11,11,7,7,31,5,7,7,11,7,23,3,15,7,15,3,23,7,7,15,15,3,15,3,23,7,7,7,29,7,7,11,11,3,23,3,15,11,15,7,23,3,7,7,23,7,19,3,11,15,7,3,31,5,15,11,11,3,15,11,19,7,7,3,35,3,15,7,15,7,15,7,11,15,15,3,27,3,7,15,17,3,23,3,23,7,7,7,23,7,7,11,19,7,31,3,11,7,7,7,31,7,7,7,23,7,15,3,23,17,7,3,23,3,15,15,15,3,23,7,11,7,15,3,39,3,11,11,11,11,15,7,15,7,15 mov $5,2 mov $7,$0 lpb $5 sub $5,1 add $0,$5 sub $0,1 mov $2,$0 mov $4,$0 mov $6,2 lpb $2 add $4,2 lpb $4 trn $4,$2 add $6,1 lpe sub $2,1 add $4,$0 lpe mov $3,$5 lpb $3 mov $1,$6 sub $3,1 lpe lpe lpb $7 sub $1,$6 mov $7,0 lpe sub $1,2 mul $1,2 add $1,1
; ;-------------------------------- ; BUZZKICK ; ------------------------------ ;#define defb db ;#define defw dw ;#define db db ;#define dw dw ;#define end end ;#define org org ;#define DEFB db ;#define DEFW dw ;#define DB db ;#define DW dw ;#define END end ;#define ORG org ;#define equ equ ;#define EQU equ ORG $8000 ;test code begin ld hl,musicdata1 ld hl,musicdata2 call play ret ;engine code play di ld (drumList+1),hl ld a,(hl) inc hl ld h,(hl) ld l,a xor a ld (songSpeedComp+1),a ld (ch1out+1),a ld (ch2out+1),a ld a,128 ld (ch1freq+1),a ld (ch2freq+1),a ld a,1 ld (ch1delay1+1),a ld (ch2delay1+1),a ld a,16 ld (ch1delay2+1),a ld (ch2delay2+1),a exx ld d,a ld e,a ld b,a ld c,a push hl exx readRow ld c,(hl) inc hl bit 7,c jr z,noSpeed ld a,(hl) inc hl or a jr nz,noLoop ld a,(hl) inc hl ld h,(hl) ld l,a jr readRow noLoop ld (songSpeed+1),a noSpeed bit 6,c jr z,noSustain1 ld a,(hl) inc hl exx ld d,a ld e,a exx noSustain1 bit 5,c jr z,noSustain2 ld a,(hl) inc hl exx ld b,a ld c,a exx noSustain2 bit 4,c jr z,noNote1 ld a,(hl) ld d,a inc hl or a jr z,$+4 ; ld a,$18 ld a, 33 ld (ch1out+1),a jr z,noNote1 ld a,d ld (ch1freq+1),a srl a srl a ld (ch1delay2+1),a ld a,1 ld (ch1delay1+1),a exx ld e,d exx noNote1 bit 3,c jr z,noNote2 ld a,(hl) ld e,a inc hl or a jr z,$+4 ; ld a,$18 ld a, 33 ld (ch2out+1),a jr z,noNote2 ld a,e ld (ch2freq+1),a srl a srl a srl a ld (ch2delay2+1),a ld a,1 ld (ch2delay1+1),a exx ld c,b exx noNote2 ld a,c and 7 jr z,noDrum playDrum push hl add a,a add a,a ld c,a ld b,0 drumList: ld hl,0 add hl,bc ld a,(hl) ;length in 256-sample blocks ld b,a inc hl inc hl add a,a add a,a ld (songSpeedComp+1),a ld a,(hl) inc hl ld h,(hl) ;sample data ld l,a ld a,1 ld (mask+1),a ld c,0 loop0 ld a,(hl) ;7 mask: and 0 ;7 sub 1 ;7 sbc a,a ;4 ; and $18 ;7 and 33 ; out ($fe),a ;11 ld (26624), a ld a,(mask+1) ;13 rlc a ;8 ld (mask+1),a ;13 jr nc,$+3 ;7/12 inc hl ;6 jr $+2 ;12 jr $+2 ;12 jr $+2 ;12 jr $+2 ;12 nop ;4 nop ;4 ld a,0 ;7 dec c ;4 jr nz,loop0 ;7/12=168t djnz loop0 pop hl noDrum songSpeed: ld a,0 ld b,a songSpeedComp: sub 0 jr nc,$+3 xor a ld c,a ld a,(songSpeedComp+1) sub b jr nc,$+3 xor a ld (songSpeedComp+1),a ld a,c or a jp z,readRow ld c,a ld b,64 soundLoop ld a,3 ;7 dec a ;4 jr nz,$-1 ;7/12=50t jr $+2 ;12 dec d ;4 jp nz,ch2 ;10 ch1freq: ld d,0 ;7 ch1delay1: ld a,0 ;7 dec a ;4 jr nz,$-1 ;7/12 ch1out: ld a,0 ;7 ; out ($fe),a ;11 and 33 ld (26624), a ch1delay2: ld a,0 ;7 dec a ;4 jr nz,$-1 ;7/12 ; out ($fe),a ;11 and 33 ld (26624), a ch2 ld a,3 ;7 dec a ;4 jr nz,$-1 ;7/12=50t jr $+2 ;12 dec e ;4 jp nz,loop ;10 ch2freq: ld e,0 ;7 ch2delay1: ld a,0 ;7 dec a ;4 jr nz,$-1 ;7/12 ch2out: ld a,0 ;7 ; out ($fe),a ;11 and 33 ld (26624), a ch2delay2: ld a,0 ;7 dec a ;4 jr nz,$-1 ;7/12 ; out ($fe),a ;11 and 33 ld (26624), a loop dec b ;4 jr nz,soundLoop ;7/12=168t ld b,64 envelopeDown exx dec e jp nz,noEnv1 ld e,d ld hl,ch1delay2+1 dec (hl) jr z,$+5 ld hl,ch1delay1+1 inc (hl) noEnv1 dec c jp nz,noEnv2 ld c,b ld hl,ch2delay2+1 dec (hl) jr z,$+5 ld hl,ch2delay1+1 inc (hl) noEnv2 exx dec c jp nz,soundLoop xor a ; in a,($fe) ; cpl ; and $1f ; jp z,readRow jp readRow pop hl exx ei ret musicdata1: speed equ $c00 db $c0 seq dw ptn0 dw ptn0 dw ptn1 dw ptn2 dw ptn1 dw ptn3 dw ptn4 dw ptn5 dw ptn4 dw ptn6 dw ptn7 dw ptn7 dw ptn8 dw ptn13 dw ptn9 dw ptn10 dw ptn11 dw ptn13 dw ptn9 dw ptn10 dw ptn11 dw ptn12 dw ptn14 dw ptn14 dw 0 ptn0 db $5,$31 db $5,$31 db $11,$31 db $14,$31 db $31,$31 db $31,$31 db $f,$31 db $f,$31 db $5,$31 db $5,$31 db $11,$31 db $14,$31 db $31,$31 db $31,$31 db $f,$31 db $f,$31 db 0 ptn1 db $5,$e4 db $5,$22 db $11,$20 db $14,$df db $31,$9f db $31,$1f db $f,$b1 db $f,$b1 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$18 db $f,$9b db 0 ptn2 db $5,$dd db $5,$1b db $11,$1d db $14,$e0 db $31,$a0 db $31,$20 db $f,$f1 db $f,$f1 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$f1 db $f,$31 db 0 ptn3 db $5,$dd db $5,$1b db $11,$1d db $14,$dd db $31,$9d db $31,$1d db $f,$f1 db $f,$f1 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$f1 db $f,$31 db 0 ptn4 db $a,$e2 db $a,$20 db $16,$22 db $19,$e5 db $31,$a5 db $31,$25 db $14,$b1 db $14,$b1 db $a,$f1 db $a,$31 db $16,$31 db $19,$e4 db $31,$a7 db $31,$25 db $14,$24 db $14,$a2 db 0 ptn5 db $5,$e4 db $5,$22 db $11,$24 db $14,$dd db $31,$9d db $31,$1d db $f,$f1 db $f,$f1 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$f1 db $f,$31 db 0 ptn6 db $8c,$e4 db $10c,$24 db $18c,$24 db $b1,$31 db $b1,$31 db $b1,$b1 db $a,$e2 db $a,$31 db $8,$e0 db $8,$31 db $7,$df db $7,$31 db 0 ptn7 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$b1 db $f,$b1 db $5,$f1 db $5,$31 db $11,$31 db $14,$f1 db $31,$b1 db $31,$31 db $f,$31 db $f,$b1 db 0 ptn8 db $7,$f1 db $7,$31 db $13,$31 db $16,$f1 db $31,$b1 db $31,$31 db $11,$b1 db $11,$b1 db $7,$f1 db $7,$31 db $13,$31 db $16,$f1 db $31,$b1 db $31,$31 db $11,$31 db $11,$b1 db 0 ptn9 db $7,$e6 db $7,$24 db $13,$26 db $16,$e9 db $31,$a9 db $31,$29 db $11,$a9 db $11,$a9 db $7,$f1 db $7,$31 db $13,$31 db $16,$e6 db $31,$a9 db $31,$26 db $11,$29 db $11,$a6 db 0 ptn10 db $7,$eb db $7,$2b db $13,$2b db $16,$eb db $31,$b1 db $31,$31 db $11,$f1 db $11,$f1 db $7,$f1 db $7,$31 db $13,$26 db $16,$f1 db $31,$a4 db $31,$31 db $11,$df db $11,$31 db 0 ptn11 db $7,$e6 db $7,$27 db $13,$26 db $16,$df db $31,$9f db $31,$1f db $11,$9f db $11,$9f db $7,$f1 db $7,$31 db $13,$31 db $16,$f1 db $31,$a6 db $31,$31 db $11,$26 db $11,$a7 db 0 ptn12 db $1a,$e6 db $1a,$26 db $18,$24 db $18,$24 db $16,$22 db $16,$22 db $15,$21 db $15,$21 db $e,$26 db $e,$26 db $c,$24 db $c,$24 db $a,$22 db $a,$22 db $9,$21 db $9,$21 db 0 ptn13 db $7,$f1 db $7,$31 db $13,$31 db $16,$f1 db $31,$b1 db $31,$31 db $11,$f1 db $11,$f1 db $7,$f1 db $7,$31 db $13,$31 db $16,$f1 db $31,$b1 db $31,$31 db $11,$f1 db $11,$31 db 0 ptn14 db $1a,$26 db $18,$24 db $16,$22 db $15,$21 db $e,$26 db $c,$24 db $a,$22 db $9,$21 db 0 musicdata2 dw $0944 dw p2 db $01,$02 db $03,$04 db $05,$06 db $07,$08 db $09,$0a db $0b,$0c db $01,$0d db $0e,$0f db $01,$02 db $03,$04 db $05,$06 db $07,$10 db $09,$11 db $0b,$12 db $05,$13 db $14,$15 db $16,$17 db $18,$19 db $1a,$17 db $1b,$1c db $1d,$1e db $1f,$20 db $1d,$1e db $21,$20 db $16,$17 db $18,$1c db $1a,$17 db $1b,$22 db $23,$24 db $25,$24 db $23,$26 db $27,$28 db $16,$17 db $18,$19 db $1a,$17 db $1b,$1c db $1d,$1e db $1f,$20 db $1d,$1e db $21,$20 db $16,$17 db $18,$1c db $1a,$17 db $1b,$22 db $29 p2: db $28 db $2a,$28 db $29,$2b db $2c,$2d db $00 p3: db $e2,$00,$e2,$00,$e2,$00,$e2,$00 db $00,$00,$38,$38,$32,$32,$2c,$2c db $2c,$00,$e2,$00,$e2,$00,$e2,$00 db $38,$38,$38,$38,$3c,$3c,$38,$38 db $97,$00,$97,$00,$97,$00,$97,$00 db $38,$38,$3c,$3c,$00,$00,$00,$00 db $2c,$00,$97,$00,$97,$00,$97,$00 db $43,$43,$3c,$3c,$00,$00,$4b,$4b db $a9,$00,$a9,$00,$a9,$00,$a9,$00 db $4b,$4b,$54,$54,$4b,$4b,$43,$43 db $2c,$00,$a9,$00,$a9,$00,$a9,$00 db $4b,$4b,$4b,$4b,$54,$54,$4b,$4b db $4b,$4b,$59,$00,$59,$00,$59,$00 db $2c,$00,$ca,$00,$b3,$00,$b3,$00 db $54,$00,$54,$00,$4b,$00,$4b,$00 db $38,$38,$32,$32,$00,$00,$3c,$3c db $3c,$3c,$43,$43,$4b,$4b,$54,$54 db $65,$65,$59,$59,$00,$00,$4b,$4b db $4b,$4b,$4b,$4b,$4b,$4b,$4b,$4b db $2c,$00,$97,$00,$2c,$00,$2c,$00 db $4b,$4b,$4b,$4b,$00,$00,$00,$00 db $a9,$00,$a9,$a9,$54,$00,$54,$54 db $43,$43,$38,$38,$32,$32,$43,$43 db $2c,$00,$a9,$a9,$54,$00,$54,$54 db $38,$38,$32,$32,$38,$38,$32,$32 db $97,$00,$97,$97,$4b,$00,$4b,$4b db $2c,$00,$97,$97,$2c,$00,$2c,$4b db $38,$38,$32,$32,$43,$43,$38,$38 db $86,$00,$86,$86,$43,$00,$43,$43 db $3c,$3c,$38,$38,$32,$32,$3c,$3c db $2c,$00,$86,$86,$43,$00,$43,$43 db $38,$38,$32,$32,$3c,$3c,$38,$38 db $2c,$00,$86,$86,$2c,$00,$2c,$43 db $38,$38,$32,$32,$43,$43,$3c,$3c db $ca,$00,$ca,$ca,$65,$00,$65,$65 db $43,$00,$43,$00,$43,$00,$43,$00 db $2c,$00,$ca,$ca,$65,$00,$65,$65 db $3c,$00,$3c,$00,$3c,$00,$3c,$00 db $2c,$00,$ca,$ca,$65,$00,$65,$00 db $38,$00,$38,$00,$38,$00,$38,$00 db $e2,$00,$e2,$e2,$71,$00,$71,$71 db $2c,$00,$e2,$e2,$71,$00,$71,$71 db $38,$38,$38,$38,$38,$38,$38,$38 db $2c,$e2,$e2,$e2,$e2,$00,$00,$00 db $38,$38,$38,$38,$38,$00,$00,$00 end
; A230658: Number of nX3 0..2 black square subarrays x(i,j) with each element diagonally or antidiagonally next to at least one element with value 2-x(i,j) ; Submitted by Jamie Morken(s3) ; 0,3,15,21,135,177,1155,1509,9855,12873,84075,109821,717255,936897,6118995,7992789,52201935,68187513,445341435,581716461,3799265175,4962698097,32412020835,42337417029,276511126815,361185960873,2358952057995,3081323979741,20124524014695,26287171974177,171684907900275,224259251848629,1464666075043695,1913184578740953,12495255043792155,16321624201274061,106598631093954615,139241879496502737,909406659670422915,1187890418663428389,7758265412657987775,10134046249984844553,66186762075240198315 mov $3,1 lpb $0 sub $0,1 mul $1,2 add $2,$3 mov $3,$1 mov $1,$2 dif $2,5 mul $2,5 lpe mov $0,$1 mul $0,3
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Linq.Enumerable #include "System/Linq/Enumerable.hpp" // Including type: System.Collections.Generic.IEnumerable`1 #include "System/Collections/Generic/IEnumerable_1.hpp" // Including type: System.Collections.Generic.IEnumerator`1 #include "System/Collections/Generic/IEnumerator_1.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections namespace System::Collections { // Skipping declaration: IEnumerator because it is already included! } // Completed forward declares #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::Linq::Enumerable::$RangeIterator$d__115); DEFINE_IL2CPP_ARG_TYPE(::System::Linq::Enumerable::$RangeIterator$d__115*, "System.Linq", "Enumerable/<RangeIterator>d__115"); // Type namespace: System.Linq namespace System::Linq { // Size: 0x30 #pragma pack(push, 1) // Autogenerated type: System.Linq.Enumerable/System.Linq.<RangeIterator>d__115 // [TokenAttribute] Offset: FFFFFFFF // [CompilerGeneratedAttribute] Offset: FFFFFFFF class Enumerable::$RangeIterator$d__115 : public ::Il2CppObject/*, public ::System::Collections::Generic::IEnumerable_1<int>, public ::System::Collections::Generic::IEnumerator_1<int>*/ { public: public: // private System.Int32 <>1__state // Size: 0x4 // Offset: 0x10 int $$1__state; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <>2__current // Size: 0x4 // Offset: 0x14 int $$2__current; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <>l__initialThreadId // Size: 0x4 // Offset: 0x18 int $$l__initialThreadId; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 start // Size: 0x4 // Offset: 0x1C int start; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 <>3__start // Size: 0x4 // Offset: 0x20 int $$3__start; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 <i>5__1 // Size: 0x4 // Offset: 0x24 int $i$5__1; // Field size check static_assert(sizeof(int) == 0x4); // private System.Int32 count // Size: 0x4 // Offset: 0x28 int count; // Field size check static_assert(sizeof(int) == 0x4); // public System.Int32 <>3__count // Size: 0x4 // Offset: 0x2C int $$3__count; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating interface conversion operator: operator ::System::Collections::Generic::IEnumerable_1<int> operator ::System::Collections::Generic::IEnumerable_1<int>() noexcept { return *reinterpret_cast<::System::Collections::Generic::IEnumerable_1<int>*>(this); } // Creating interface conversion operator: operator ::System::Collections::Generic::IEnumerator_1<int> operator ::System::Collections::Generic::IEnumerator_1<int>() noexcept { return *reinterpret_cast<::System::Collections::Generic::IEnumerator_1<int>*>(this); } // Get instance field reference: private System.Int32 <>1__state [[deprecated("Use field access instead!")]] int& dyn_$$1__state(); // Get instance field reference: private System.Int32 <>2__current [[deprecated("Use field access instead!")]] int& dyn_$$2__current(); // Get instance field reference: private System.Int32 <>l__initialThreadId [[deprecated("Use field access instead!")]] int& dyn_$$l__initialThreadId(); // Get instance field reference: private System.Int32 start [[deprecated("Use field access instead!")]] int& dyn_start(); // Get instance field reference: public System.Int32 <>3__start [[deprecated("Use field access instead!")]] int& dyn_$$3__start(); // Get instance field reference: private System.Int32 <i>5__1 [[deprecated("Use field access instead!")]] int& dyn_$i$5__1(); // Get instance field reference: private System.Int32 count [[deprecated("Use field access instead!")]] int& dyn_count(); // Get instance field reference: public System.Int32 <>3__count [[deprecated("Use field access instead!")]] int& dyn_$$3__count(); // private System.Int32 System.Collections.Generic.IEnumerator<System.Int32>.get_Current() // Offset: 0xEA7C20 int System_Collections_Generic_IEnumerator$System_Int32$_get_Current(); // private System.Object System.Collections.IEnumerator.get_Current() // Offset: 0xEA7C68 ::Il2CppObject* System_Collections_IEnumerator_get_Current(); // public System.Void .ctor(System.Int32 <>1__state) // Offset: 0xEA7B80 template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static Enumerable::$RangeIterator$d__115* New_ctor(int $$1__state) { static auto ___internal__logger = ::Logger::get().WithContext("::System::Linq::Enumerable::$RangeIterator$d__115::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<Enumerable::$RangeIterator$d__115*, creationType>($$1__state))); } // private System.Void System.IDisposable.Dispose() // Offset: 0xEA7BB8 void System_IDisposable_Dispose(); // private System.Boolean MoveNext() // Offset: 0xEA7BBC bool MoveNext(); // private System.Void System.Collections.IEnumerator.Reset() // Offset: 0xEA7C28 void System_Collections_IEnumerator_Reset(); // private System.Collections.Generic.IEnumerator`1<System.Int32> System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator() // Offset: 0xEA7CC8 ::System::Collections::Generic::IEnumerator_1<int>* System_Collections_Generic_IEnumerable$System_Int32$_GetEnumerator(); // private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() // Offset: 0xEA7D78 ::System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator(); }; // System.Linq.Enumerable/System.Linq.<RangeIterator>d__115 #pragma pack(pop) static check_size<sizeof(Enumerable::$RangeIterator$d__115), 44 + sizeof(int)> __System_Linq_Enumerable_$RangeIterator$d__115SizeCheck; static_assert(sizeof(Enumerable::$RangeIterator$d__115) == 0x30); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_Generic_IEnumerator$System_Int32$_get_Current // Il2CppName: System.Collections.Generic.IEnumerator<System.Int32>.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_Generic_IEnumerator$System_Int32$_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.Collections.Generic.IEnumerator<System.Int32>.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerator_get_Current // Il2CppName: System.Collections.IEnumerator.get_Current template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerator_get_Current)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.Collections.IEnumerator.get_Current", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_IDisposable_Dispose // Il2CppName: System.IDisposable.Dispose template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_IDisposable_Dispose)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.IDisposable.Dispose", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::MoveNext // Il2CppName: MoveNext template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::MoveNext)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "MoveNext", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerator_Reset // Il2CppName: System.Collections.IEnumerator.Reset template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerator_Reset)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.Collections.IEnumerator.Reset", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_Generic_IEnumerable$System_Int32$_GetEnumerator // Il2CppName: System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::Generic::IEnumerator_1<int>* (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_Generic_IEnumerable$System_Int32$_GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.Collections.Generic.IEnumerable<System.Int32>.GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerable_GetEnumerator // Il2CppName: System.Collections.IEnumerable.GetEnumerator template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Collections::IEnumerator* (System::Linq::Enumerable::$RangeIterator$d__115::*)()>(&System::Linq::Enumerable::$RangeIterator$d__115::System_Collections_IEnumerable_GetEnumerator)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::Linq::Enumerable::$RangeIterator$d__115*), "System.Collections.IEnumerable.GetEnumerator", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
; A040037: Continued fraction for sqrt(44). ; 6,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1,2,1,1,1,12,1,1,1 seq $0,40329 ; Continued fraction for sqrt(348). div $0,3 trn $0,1 add $0,1
; float __sint2fs_callee(signed int si) SECTION code_fp_math48 PUBLIC cm48_sdccixp_sint2ds_callee EXTERN am48_double16, cm48_sdccixp_m482d cm48_sdccixp_sint2ds_callee: ; signed int to double ; ; enter : stack = signed int si, ret ; ; exit : dehl = sdcc_float(si) ; ; uses : af, bc, de, hl, bc', de', hl' pop af pop hl push af call am48_double16 jp cm48_sdccixp_m482d
/* This file is a part of: Lina Engine https://github.com/inanevin/LinaEngine Author: Inan Evin http://www.inanevin.com Copyright (c) [2018-2020] [Inan Evin] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "Modals/SelectMeshModal.hpp" #include "Widgets/WidgetsUtility.hpp" #include "imgui/imgui.h" namespace LinaEditor { void SelectMeshModal::Draw(const std::map<int, LinaEngine::Graphics::Mesh>& map, int* selectedMeshID, std::string& selectedMeshPath) { ImGui::BeginChild("SelectMeshModalChild", ImVec2(0, 300), true); static int selected = -1; static std::string selectedPath = ""; for (std::map<int, LinaEngine::Graphics::Mesh>::const_iterator it = map.begin(); it != map.end(); it++) { WidgetsUtility::IncrementCursorPosY(5); WidgetsUtility::IncrementCursorPosX(5); if (ImGui::Selectable(it->second.GetPath().c_str(), selected == it->second.GetID())) { selected = it->second.GetID(); selectedPath = it->second.GetPath(); } } ImGui::EndChild(); WidgetsUtility::IncrementCursorPosY(15); WidgetsUtility::IncrementCursorPosX(10); if (WidgetsUtility::Button("Add Selected", ImVec2(ImGui::GetWindowSize().x * 0.5f - 20, 0.0f))) { *selectedMeshID = selected; selectedMeshPath = selectedPath; ImGui::CloseCurrentPopup(); } ImGui::SameLine(); WidgetsUtility::IncrementCursorPosX(10); if (WidgetsUtility::Button("Close", ImVec2(ImGui::GetWindowSize().x * 0.5f - 20, 0.0f))) { ImGui::CloseCurrentPopup(); } } }
; A137512: The number of nodes visible from underneath a binary tree, where the nodes are placed such that the innermost of the two sprouting nodes should be underneath the mother. ; 1,1,2,3,3,3,4,5,5,6,6,6,7,7,8,9,9,10,10,11,11,12,12,12,13,13,14,14,15,15,16 mov $2,$0 add $0,4 lpb $2 div $2,2 mov $1,$2 trn $2,1 lpe add $0,$1 div $0,2 sub $0,1
; struct astar_path __FASTCALL__ *astar_SearchResume(struct astar_path *p) ; resume a search previously stopped ; 01.2007 aralbrec XLIB astar_SearchResume LIB astar_Search XREF ASMDISP_ASTAR_SEARCH_RESUME_SUCCESS, ASMDISP_ASTAR_SEARCH_RESUME_FAIL ; enter : hl = path to start search with ; if 0, search not resumed from path but from queue .astar_SearchResume ld a,h or l jp z, astar_Search + ASMDISP_ASTAR_SEARCH_RESUME_SUCCESS jp astar_Search + ASMDISP_ASTAR_SEARCH_RESUME_FAIL
; $Id: VMMRC99.asm $ ;; @file ; VMMRC99 - The last object module in the link. ; ; Copyright (C) 2006-2015 Oracle Corporation ; ; This file is part of VirtualBox Open Source Edition (OSE), as ; available from http://www.virtualbox.org. This file is free software; ; you can redistribute it and/or modify it under the terms of the GNU ; General Public License (GPL) as published by the Free Software ; Foundation, in version 2 as it comes in the "COPYING" file of the ; VirtualBox OSE distribution. VirtualBox OSE is distributed in the ; hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. ; %include "VMMRC.mac" ;; ; End the Trap0b segment. VMMR0_SEG Trap0b GLOBALNAME g_aTrap0bHandlersEnd dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ;; ; End the Trap0d segment. VMMR0_SEG Trap0d GLOBALNAME g_aTrap0dHandlersEnd dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ;; ; End the Trap0e segment. VMMR0_SEG Trap0e GLOBALNAME g_aTrap0eHandlersEnd dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ;; ; End the patch helper segment BEGIN_PATCH_HLP_SEG EXPORTEDNAME g_PatchHlpEnd dd 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
#include "gtest/gtest.h" #include <vector> #include "cfdcore/cfdcore_common.h" #include "cfdcore/cfdcore_logger.h" using cfd::core::logger::IsEnableLogLevel; using cfd::core::logger::WriteLog; using cfd::core::logger::CfdLogLevel; using cfd::core::logger::CfdLogger; using cfd::core::logger::CfdSourceLocation; using cfd::core::InitializeLogger; using cfd::core::FinalizeLogger; using cfd::core::SetLogger; TEST(CfdLogger, IsEnableLogLevel) { EXPECT_FALSE(IsEnableLogLevel(CfdLogLevel::kCfdLogLevelTrace)); } TEST(CfdLogger, WriteLog) { CfdSourceLocation loc {"", 0, ""}; EXPECT_NO_THROW((WriteLog(loc, CfdLogLevel::kCfdLogLevelInfo, ""))); } TEST(CfdLogger, FinalizeLogger) { EXPECT_NO_THROW((FinalizeLogger())); } TEST(CfdLogger, InitializeLogger) { EXPECT_NO_THROW((InitializeLogger())); } TEST(CfdLogger, SetLogger) { EXPECT_NO_THROW((SetLogger(nullptr))); } TEST(CfdLogger, Destructor) { CfdLogger logger; EXPECT_NO_THROW((logger = CfdLogger())); }
db 0 ; species ID placeholder db 35, 40, 40, 35, 25, 45 ; hp atk def spd sat sdf db BUG, POISON ; type db 255 ; catch rate db 52 ; base exp db NO_ITEM, NO_ITEM ; items db GENDER_F50 ; gender ratio db 100 ; unknown 1 db 15 ; step cycles to hatch db 5 ; unknown 2 INCBIN "gfx/pokemon/weedle/front.dimensions" db 0, 0, 0, 0 ; padding db GROWTH_MEDIUM_FAST ; growth rate dn EGG_BUG, EGG_BUG ; egg groups ; tm/hm learnset tmhm LEECH_LIFE ; end
; A032797: Numbers n such that n(n+1)(n+2)...(n+10) /(n+(n+1)+(n+2)+...+(n+10)) is a multiple of n. ; 1,2,3,4,5,7,8,9,10,12,13,14,15,16,18,19,20,21,23,24,25,26,27,29,30,31,32,34,35,36,37,38,40,41,42,43,45,46,47,48,49,51,52,53,54,56,57,58,59,60,62,63,64,65,67,68,69,70,71,73,74,75,76,78,79,80,81,82,84,85,86 mov $1,11 mul $1,$0 div $1,9 add $1,1 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r12 push %r14 push %r9 push %rbp push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0x1a9ae, %r14 nop nop nop nop sub %r9, %r9 mov $0x6162636465666768, %rbp movq %rbp, %xmm4 movups %xmm4, (%r14) sub $46328, %rdx lea addresses_WT_ht+0x11fae, %r11 nop nop nop nop nop sub %rdx, %rdx movb $0x61, (%r11) nop nop nop nop cmp $6561, %rbp lea addresses_A_ht+0x12b7e, %rsi lea addresses_WT_ht+0x9179, %rdi clflush (%rsi) nop nop nop dec %r9 mov $23, %rcx rep movsb sub $32530, %r9 lea addresses_WC_ht+0x36ee, %rsi add %r12, %r12 mov (%rsi), %r14 nop and %rsi, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbp pop %r9 pop %r14 pop %r12 pop %r11 ret .global s_faulty_load s_faulty_load: push %r11 push %r12 push %r13 push %r14 push %r9 push %rax push %rdx // Load lea addresses_PSE+0xb1be, %r11 nop nop nop cmp %r9, %r9 mov (%r11), %r13d nop nop nop nop xor %rdx, %rdx // Store lea addresses_PSE+0x1b890, %rax nop and $45743, %rdx movl $0x51525354, (%rax) nop nop nop inc %r9 // Faulty Load lea addresses_D+0x52ae, %r14 and $32100, %r12 mov (%r14), %eax lea oracles, %r14 and $0xff, %rax shlq $12, %rax mov (%r14,%rax,1), %rax pop %rdx pop %rax pop %r9 pop %r14 pop %r13 pop %r12 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 0}} {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 4}} {'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 1}} [Faulty Load] {'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_D', 'same': True, 'AVXalign': False, 'congruent': 0}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_WT_ht', 'same': False, 'AVXalign': False, 'congruent': 8}} {'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': False, 'congruent': 7}} {'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_A_ht', 'congruent': 3}, 'dst': {'same': True, 'type': 'addresses_WT_ht', 'congruent': 0}} {'OP': 'LOAD', 'src': {'size': 8, 'NT': True, 'type': 'addresses_WC_ht', 'same': False, 'AVXalign': False, 'congruent': 6}} {'36': 21829} 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 36 */
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Description: * context for replica with different roles * * Revision history: * Mar., 2015, @imzhenyu (Zhenyu Guo), first version * xxxx-xx-xx, author, fix bug about xxx */ #include <dsn/utility/filesystem.h> #include <dsn/utility/utils.h> #include "replica_context.h" #include "replica.h" #include "replica_stub.h" #include "mutation.h" #include "mutation_log.h" #include "block_service/block_service_manager.h" namespace dsn { namespace replication { void primary_context::cleanup(bool clean_pending_mutations) { do_cleanup_pending_mutations(clean_pending_mutations); // clean up group check CLEANUP_TASK_ALWAYS(group_check_task) for (auto it = group_check_pending_replies.begin(); it != group_check_pending_replies.end(); ++it) { CLEANUP_TASK_ALWAYS(it->second) // it->second->cancel(true); } group_check_pending_replies.clear(); // clean up reconfiguration CLEANUP_TASK_ALWAYS(reconfiguration_task) // clean up checkpoint CLEANUP_TASK_ALWAYS(checkpoint_task) // cleanup group bulk load for (auto &kv : group_bulk_load_pending_replies) { CLEANUP_TASK_ALWAYS(kv.second); } group_bulk_load_pending_replies.clear(); membership.ballot = 0; cleanup_bulk_load_states(); cleanup_split_states(); secondary_disk_status.clear(); } bool primary_context::is_cleaned() { return nullptr == group_check_task && nullptr == reconfiguration_task && nullptr == checkpoint_task && group_check_pending_replies.empty() && nullptr == register_child_task && nullptr == query_child_task && group_bulk_load_pending_replies.empty(); } void primary_context::do_cleanup_pending_mutations(bool clean_pending_mutations) { if (clean_pending_mutations) { write_queue.clear(); } } void primary_context::reset_membership(const partition_configuration &config, bool clear_learners) { statuses.clear(); if (clear_learners) { learners.clear(); } if (config.ballot > membership.ballot) next_learning_version = (((uint64_t)config.ballot) << 32) + 1; else ++next_learning_version; membership = config; if (membership.primary.is_invalid() == false) { statuses[membership.primary] = partition_status::PS_PRIMARY; } for (auto it = config.secondaries.begin(); it != config.secondaries.end(); ++it) { statuses[*it] = partition_status::PS_SECONDARY; learners.erase(*it); } for (auto it = learners.begin(); it != learners.end(); ++it) { statuses[it->first] = partition_status::PS_POTENTIAL_SECONDARY; } } void primary_context::get_replica_config(partition_status::type st, /*out*/ replica_configuration &config, uint64_t learner_signature /*= invalid_signature*/) { config.pid = membership.pid; config.primary = membership.primary; config.ballot = membership.ballot; config.status = st; config.learner_signature = learner_signature; } bool primary_context::check_exist(::dsn::rpc_address node, partition_status::type st) { switch (st) { case partition_status::PS_PRIMARY: return membership.primary == node; case partition_status::PS_SECONDARY: return std::find(membership.secondaries.begin(), membership.secondaries.end(), node) != membership.secondaries.end(); case partition_status::PS_POTENTIAL_SECONDARY: return learners.find(node) != learners.end(); default: dassert(false, "invalid partition_status, status = %s", enum_to_string(st)); return false; } } void primary_context::reset_node_bulk_load_states(const rpc_address &node) { secondary_bulk_load_states[node].__set_download_progress(0); secondary_bulk_load_states[node].__set_download_status(ERR_OK); secondary_bulk_load_states[node].__set_ingest_status(ingestion_status::IS_INVALID); secondary_bulk_load_states[node].__set_is_cleaned_up(false); secondary_bulk_load_states[node].__set_is_paused(false); } void primary_context::cleanup_bulk_load_states() { secondary_bulk_load_states.erase(secondary_bulk_load_states.begin(), secondary_bulk_load_states.end()); ingestion_is_empty_prepare_sent = false; } void primary_context::cleanup_split_states() { CLEANUP_TASK_ALWAYS(register_child_task) CLEANUP_TASK_ALWAYS(query_child_task) caught_up_children.clear(); sync_send_write_request = false; split_stopped_secondary.clear(); } bool primary_context::secondary_disk_space_insufficient() const { for (const auto &kv : secondary_disk_status) { if (kv.second == disk_status::SPACE_INSUFFICIENT) { ddebug_f("partition[{}] secondary[{}] disk space is insufficient", membership.pid, kv.first.to_string()); return true; } } return false; } bool secondary_context::cleanup(bool force) { CLEANUP_TASK(checkpoint_task, force) if (!force) { CLEANUP_TASK_ALWAYS(checkpoint_completed_task); } else { CLEANUP_TASK(checkpoint_completed_task, force) } CLEANUP_TASK(catchup_with_private_log_task, force) checkpoint_is_running = false; return true; } bool secondary_context::is_cleaned() { return checkpoint_is_running == false; } bool potential_secondary_context::cleanup(bool force) { task_ptr t = nullptr; if (!force) { CLEANUP_TASK_ALWAYS(delay_learning_task) CLEANUP_TASK_ALWAYS(learning_task) CLEANUP_TASK_ALWAYS(learn_remote_files_completed_task) CLEANUP_TASK_ALWAYS(completion_notify_task) } else { CLEANUP_TASK(delay_learning_task, true) CLEANUP_TASK(learning_task, true) CLEANUP_TASK(learn_remote_files_completed_task, true) CLEANUP_TASK(completion_notify_task, true) } CLEANUP_TASK(learn_remote_files_task, force) CLEANUP_TASK(catchup_with_private_log_task, force) learning_version = 0; learning_start_ts_ns = 0; learning_copy_file_count = 0; learning_copy_file_size = 0; learning_copy_buffer_size = 0; learning_round_is_running = false; if (learn_app_concurrent_count_increased) { --owner_replica->get_replica_stub()->_learn_app_concurrent_count; learn_app_concurrent_count_increased = false; } learning_start_prepare_decree = invalid_decree; first_learn_start_decree = invalid_decree; learning_status = learner_status::LearningInvalid; return true; } bool potential_secondary_context::is_cleaned() { return nullptr == delay_learning_task && nullptr == learning_task && nullptr == learn_remote_files_task && nullptr == learn_remote_files_completed_task && nullptr == catchup_with_private_log_task && nullptr == completion_notify_task; } bool partition_split_context::cleanup(bool force) { CLEANUP_TASK(async_learn_task, force) if (!force) { CLEANUP_TASK_ALWAYS(check_state_task) } else { CLEANUP_TASK(check_state_task, force) } splitting_start_ts_ns = 0; splitting_start_async_learn_ts_ns = 0; splitting_copy_file_count = 0; splitting_copy_file_size = 0; parent_gpid.set_app_id(0); is_prepare_list_copied = false; is_caught_up = false; return true; } bool partition_split_context::is_cleaned() const { return async_learn_task == nullptr && check_state_task == nullptr; } } // namespace replication } // namespace dsn
SECTION code_driver SECTION code_driver_terminal_output PUBLIC rc_01_output_hbios1_iterm_msg_bell EXTERN rc_01_output_hbios1_oterm_msg_bell_0 rc_01_output_hbios1_iterm_msg_bell: ; can use: af, bc, de, hl bit 1,(ix+7) ret z ; if signal bell is disabled jp rc_01_output_hbios1_oterm_msg_bell_0
.data message: .asciiz "Fim da Execução" space: .asciiz " " .text main: addi $t0,$zero,0 addi $t1,$zero,0 addi $t2,$zero,0 loop: bgt $t0,9,exit add $t0,$t0,1 li $v0, 5 # chama função para ler syscall la $t7, ($v0) # carrega o inteiro lido em $t7 bgt $t1,$t7,valorMinimo blt $t2,$t7,valorMaximo j loop exit: #fim da execução li $v0, 10 syscall valorMaximo: la $t3, ($t1) li $v0, 1 add $a0,$t3,$zero syscall li $v0, 4 la $a0,space syscall jr $ra valorMinimo: la $t4, ($t2) li $v0, 1 add $a0,$t4,$zero syscall li $v0, 4 la $a0,space syscall jr $ra
#include <syntax_tree.hpp>
#ifndef SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_OPERATOR_UNARY_PLUS_HPP #define SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_OPERATOR_UNARY_PLUS_HPP #include <type_traits> #include <sprout/config.hpp> #include <sprout/tuple/tuple.hpp> #include <sprout/weed/eval_result.hpp> #include <sprout/weed/limited.hpp> #include <sprout/weed/expr/tag.hpp> #include <sprout/weed/expr/eval.hpp> #include <sprout/weed/attr_cnv/result_of/times.hpp> #include <sprout/weed/attr_cnv/times.hpp> #include <sprout/weed/traits/expr/tag_of.hpp> #include <sprout/weed/traits/parser/attribute_of.hpp> #include <sprout/weed/traits/parser/limit_of.hpp> #include <sprout/weed/context/parse_context_fwd.hpp> namespace sprout { namespace weed { // // parse_context::eval // template<typename Iterator> template<typename Expr> struct parse_context<Iterator>::eval< Expr, typename std::enable_if< std::is_same< typename sprout::weed::traits::tag_of<Expr>::type, sprout::weed::tag::unary_plus >::value >::type > { private: typedef sprout::weed::parse_context<Iterator> context_type; typedef typename sprout::tuples::tuple_element<0, typename Expr::args_type>::type expr_type; typedef typename sprout::weed::traits::limit_of<expr_type, Iterator, context_type>::type limit; typedef typename sprout::weed::traits::attribute_of<expr_type, Iterator, context_type>::type attr_type; public: typedef typename sprout::weed::attr_cnv::result_of::times< limit::value, typename sprout::weed::traits::attribute_of<expr_type, Iterator, context_type>::type >::type attribute_type; typedef sprout::weed::eval_result<context_type, Iterator, attribute_type> result_type; private: template<typename Result, typename Head, typename... Attrs> SPROUT_CONSTEXPR typename std::enable_if< sizeof...(Attrs) + 1 == limit::value, result_type >::type call( expr_type const& expr, context_type const& ctx, sprout::weed::limited::category limited_category, Result const& res, Head const& head, Attrs const&... attrs ) const { return res.success() ? limited_category == sprout::weed::limited::discard ? call( expr, res.ctx(), limited_category, sprout::weed::eval(expr, res.ctx()), head, attrs... ) : call( expr, res.ctx(), limited_category, sprout::weed::eval(expr, res.ctx()), attrs..., res.attr() ) : result_type( true, ctx.begin(), sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs...), ctx ) ; } template<typename Result, typename Head, typename... Attrs> SPROUT_CONSTEXPR typename std::enable_if< sizeof...(Attrs) + 2 == limit::value, result_type >::type call( expr_type const& expr, context_type const& ctx, sprout::weed::limited::category limited_category, Result const& res, Head const& head, Attrs const&... attrs ) const { return res.success() ? limited_category != sprout::weed::limited::stopover ? call( expr, res.ctx(), limited_category, sprout::weed::eval(expr, res.ctx()), head, attrs..., res.attr() ) : result_type( true, res.current(), sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs..., res.attr()), res.ctx() ) : result_type( true, ctx.begin(), sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs...), ctx ) ; } template<typename Result, typename Head, typename... Attrs> SPROUT_CONSTEXPR typename std::enable_if< (sizeof...(Attrs) + 2 < limit::value), result_type >::type call( expr_type const& expr, context_type const& ctx, sprout::weed::limited::category limited_category, Result const& res, Head const& head, Attrs const&... attrs ) const { return res.success() ? call( expr, res.ctx(), limited_category, sprout::weed::eval(expr, res.ctx()), head, attrs..., res.attr() ) : result_type( true, ctx.begin(), sprout::weed::attr_cnv::times<limit::value, attr_type>(head, attrs...), ctx ) ; } template<typename Result> SPROUT_CONSTEXPR result_type call_inf( expr_type const& expr, context_type const& ctx, Result const& res ) const { return res.success() ? call_inf(expr, res.ctx(), sprout::weed::eval(expr, res.ctx())) : result_type(true, ctx.begin(), attribute_type(), ctx) ; } template<bool Infinity, typename Result> SPROUT_CONSTEXPR typename std::enable_if< Infinity, result_type >::type call( expr_type const& expr, context_type const& ctx, Result const& res ) const { return res.success() ? call_inf(expr, res.ctx(), sprout::weed::eval(expr, res.ctx())) : result_type(false, ctx.begin(), attribute_type(), ctx) ; } template<bool Infinity, typename Result> SPROUT_CONSTEXPR typename std::enable_if< !Infinity, result_type >::type call( expr_type const& expr, context_type const& ctx, Result const& res ) const { return res.success() ? call( expr, res.ctx(), sprout::tuples::get<0>(expr.args()).limited_category(), sprout::weed::eval(expr, res.ctx()), res.attr() ) : result_type(false, ctx.begin(), attribute_type(), ctx) ; } public: SPROUT_CONSTEXPR result_type operator()( Expr const& expr, context_type const& ctx ) const { return call<limit::value == std::size_t(-1)>( sprout::tuples::get<0>(expr.args()), ctx, sprout::weed::eval(sprout::tuples::get<0>(expr.args()), ctx) ); } }; } // namespace weed } // namespace sprout #endif // #ifndef SPROUT_WEED_CONTEXT_PARSE_CONTEXT_TERMINAL_OPERATOR_UNARY_PLUS_HPP
GLOBAL set_interrupts GLOBAL int_21_hand GLOBAL int_20_hand GLOBAL int_80_hand GLOBAL mascaraPIC1,mascaraPIC2 GLOBAL write_byte_to_port_0x70 GLOBAL write_byte_to_port_0x71 GLOBAL read_byte_from_port_0x71 GLOBAL play_sound_asm GLOBAL stop_sound_asm GLOBAL yield GLOBAL outb GLOBAL inb GLOBAL clear_interrupts GLOBAL userToKernel GLOBAL kernelToUser extern keyboard_interrupt extern timer_interrupt extern syscall_handler extern schedule extern kernelStack extern userSchedToKernel extern kernelSchedToUser extern setNextProcess %macro pushaq 0 push rax push rbx push rcx push rdx push rbp push rdi push rsi push r8 push r9 push r10 push r11 push r12 push r13 push r14 push r15 push fs push gs %endmacro %macro popaq 0 pop gs pop fs pop r15 pop r14 pop r13 pop r12 pop r11 pop r10 pop r9 pop r8 pop rsi pop rdi pop rbp pop rdx pop rcx pop rbx pop rax %endmacro section .text yield: int 0x81 ret int_20_hand: ; Handler de INT 20 ( Timer Tick ) pushaq ; Se salvan los registros call timer_interrupt mov rdi, rsp call userSchedToKernel mov rsp, rax call setNextProcess call kernelSchedToUser mov rsp, rax mov rax, 0 mov al, 20h ; Envio de EOI generico al PIC out 20h,al popaq iretq outb: ;outb(value, port) mov rdx, rsi mov rax, rdi out dx, al ret inb: mov rax, 0 ;inb(value) mov rdx, rdi in al, dx mov rax, rdi ret int_21_hand: ; Handler de INT 21 ( Teclado ) pushaq ; Se salvan los registros in al, 60h ; Leo el puerto del teclado mov rdi, rax call keyboard_interrupt mov al,20h ; Envio de EOI generico al PIC out 20h,al popaq iretq int_80_hand: ; Handler de INT 80 ( llamada al systema ) pushaq ; Se salvan los registros mov rdi, rcx ; Se pasa en rdi el puntero asl buffer mov rsi, rdx ; Se pasa en rsi el tamaño del buffer mov rdx, rax ; Se pasa en rdx a que syscall se esta llamando call syscall_handler popaq iretq set_interrupts: sti ret clear_interrupts: cli ret mascaraPIC1: ; Escribe mascara del PIC 1 push rbp mov rbp, rsp mov rax, rdi out 21h, al mov rsp,rbp pop rbp ret mascaraPIC2: ; Escribe mascara del PIC 2 push rbp mov rbp, rsp mov rax, rdi out 0A1h, al mov rsp,rbp pop rbp ret read_byte_from_port_0x71: ; Se comunica con el RTC xor eax, eax in al, 0x71 ret write_byte_to_port_0x70: ; Se comunica con el RTC mov rax, rdi out 0x70, al ret write_byte_to_port_0x71: ; Se comunica con el RTC mov rax, rdi out 0x71, al ret play_sound_asm: push rbp mov rbp, rsp mov al, 182 ; Prepare the speaker for the out 43h, al ; note. mov ax, di ; Frequency number (in decimal) ; for middle C. out 42h, al ; Output low byte. mov al, ah ; Output high byte. out 42h, al in al, 61h ; Turn on note (get value from ; port 61h). or al, 00000011b ; Set bits 1 and 0. out 61h, al ; Send new value. mov rsp,rbp pop rbp ret stop_sound_asm: push rbp mov rbp, rsp mov al, 0 ; Reset bits 1 and 0. out 61h, al ; Send new value. mov rsp,rbp pop rbp ret ;SoundBlasterosOS userToKernel: pop QWORD[ret_addr] mov QWORD[proc_stack], rsp mov rsp, QWORD[kernelStack] push QWORD[ret_addr] ret ;SoundBlasterosOS kernelToUser: pop QWORD[ret_addr] mov QWORD[kernelStack], rsp mov rsp, QWORD[proc_stack] push QWORD[ret_addr] ret section .bss ret_addr: resq 1 proc_stack: resq 1
;main source code ;@author strawberrylin .386 data segment use16 bufc db '1:Input the name and score',0ah,0dh, '2:Figure the sum and the average score',0ah,0dh, '3:Sort the score',0ah,0dh, '4:Output the score from high to low',0ah,0dh, 'Enter your choose:','$' buft2 db 0ah,0dh,'Input name:$' buft3 db 0ah,0dh,'Input chinese score:$' buft4 db 0ah,0dh,'Input math score:$' buft5 db 0ah,0dh,'Input english score:$' buf db 20 db ? db 20 dup(0) store db 200 dup(0) sum dw 0 avr db 0 data ends stack segment use16 stack db 200 dup(0) stack ends code segment use16 assume ds:data,cs:code,ss:stack start: mov ax, data mov ds, ax lea di, store ; 信息储存位置 mov cx, 0 ; 学生数 show: lea dx, bufc mov ah, 9 int 21h mov ah, 1 ;input choose int 21h cmp al, '1' jz function1 cmp al, '2' jz function2 cmp al, '3' jz function3 cmp al, '4' jz function4 jmp show function1: call far ptr INFOIN jmp show function2: function3: function4: mov ah, 4ch int 21h code ends ;子程序名:INFOIN ;功能:录入学生信息 ;入口参数:储存学生信息的内存地址的di ;出口参数:无 proce segment use16 assume cs:proce INFOIN proc far inc cx push dx push ax push cx push si lea dx, buft2 ;input name mov ah, 9 int 21h lea dx, buf mov ah, 10 int 21h mov cl, buf+1 mov ch, 0 lea si, buf+2 begin: mov al, [si] mov [di], al inc si inc di dec cx jnz begin mov cl, buf+1 mov ch, 0 add di, 10 sub di, cx lea dx, buft3 ;input chns mov ah, 9 int 21h call GSCORE lea dx, buft4 ;Input maths mov ah, 9 int 21h call GSCORE lea dx, buft5 ;Input engs mov ah, 9 int 21h call GSCORE mov ax, 0 mov dx, 0 mov dl, [di-1] add ax,dx mov dl, [di-2] add ax, dx mov dl, [di-3] add ax, dx mov WORD PTR[di], ax mov dx, 0 mov dl, 3 div dl inc di inc di mov [di], al inc di pop si pop cx pop ax pop dx ret INFOIN endp ;子程序名:GSCORE ;功能:得到输入的成绩 ;入口参数:储存学生信息的偏移地址di ;出口参数:ax,存储对应的成绩 GSCORE proc push dx push bx push si push cx lea dx, buf mov ah, 10 int 21h mov cl, buf+1 lea si, buf+2 mov ax, 0 loapi: mov bl, [si] sub bl, 30h mov bh, 0 imul ax, 10 add ax, bx inc si dec cx jnz loapi mov [di], al inc di pop cx pop si pop bx pop dx ret GSCORE endp proce ends end start
_kill: file format elf32-i386 Disassembly of section .text: 00000000 <main>: #include "stat.h" #include "user.h" int main(int argc, char **argv) { 0: 55 push %ebp 1: 89 e5 mov %esp,%ebp 3: 83 e4 f0 and $0xfffffff0,%esp 6: 83 ec 20 sub $0x20,%esp int i; if(argc < 1){ 9: 83 7d 08 00 cmpl $0x0,0x8(%ebp) d: 7f 19 jg 28 <main+0x28> printf(2, "usage: kill pid...\n"); f: c7 44 24 04 0b 08 00 movl $0x80b,0x4(%esp) 16: 00 17: c7 04 24 02 00 00 00 movl $0x2,(%esp) 1e: e8 21 04 00 00 call 444 <printf> exit(); 23: e8 8c 02 00 00 call 2b4 <exit> } for(i=1; i<argc; i++) 28: c7 44 24 1c 01 00 00 movl $0x1,0x1c(%esp) 2f: 00 30: eb 26 jmp 58 <main+0x58> kill(atoi(argv[i])); 32: 8b 44 24 1c mov 0x1c(%esp),%eax 36: 8d 14 85 00 00 00 00 lea 0x0(,%eax,4),%edx 3d: 8b 45 0c mov 0xc(%ebp),%eax 40: 01 d0 add %edx,%eax 42: 8b 00 mov (%eax),%eax 44: 89 04 24 mov %eax,(%esp) 47: e8 df 01 00 00 call 22b <atoi> 4c: 89 04 24 mov %eax,(%esp) 4f: e8 90 02 00 00 call 2e4 <kill> if(argc < 1){ printf(2, "usage: kill pid...\n"); exit(); } for(i=1; i<argc; i++) 54: ff 44 24 1c incl 0x1c(%esp) 58: 8b 44 24 1c mov 0x1c(%esp),%eax 5c: 3b 45 08 cmp 0x8(%ebp),%eax 5f: 7c d1 jl 32 <main+0x32> kill(atoi(argv[i])); exit(); 61: e8 4e 02 00 00 call 2b4 <exit> 66: 66 90 xchg %ax,%ax 00000068 <stosb>: "cc"); } static inline void stosb(void *addr, int data, int cnt) { 68: 55 push %ebp 69: 89 e5 mov %esp,%ebp 6b: 57 push %edi 6c: 53 push %ebx asm volatile("cld; rep stosb" : 6d: 8b 4d 08 mov 0x8(%ebp),%ecx 70: 8b 55 10 mov 0x10(%ebp),%edx 73: 8b 45 0c mov 0xc(%ebp),%eax 76: 89 cb mov %ecx,%ebx 78: 89 df mov %ebx,%edi 7a: 89 d1 mov %edx,%ecx 7c: fc cld 7d: f3 aa rep stos %al,%es:(%edi) 7f: 89 ca mov %ecx,%edx 81: 89 fb mov %edi,%ebx 83: 89 5d 08 mov %ebx,0x8(%ebp) 86: 89 55 10 mov %edx,0x10(%ebp) "=D" (addr), "=c" (cnt) : "0" (addr), "1" (cnt), "a" (data) : "memory", "cc"); } 89: 5b pop %ebx 8a: 5f pop %edi 8b: 5d pop %ebp 8c: c3 ret 0000008d <strcpy>: #include "user.h" #include "x86.h" char* strcpy(char *s, char *t) { 8d: 55 push %ebp 8e: 89 e5 mov %esp,%ebp 90: 83 ec 10 sub $0x10,%esp char *os; os = s; 93: 8b 45 08 mov 0x8(%ebp),%eax 96: 89 45 fc mov %eax,-0x4(%ebp) while((*s++ = *t++) != 0) 99: 90 nop 9a: 8b 45 0c mov 0xc(%ebp),%eax 9d: 8a 10 mov (%eax),%dl 9f: 8b 45 08 mov 0x8(%ebp),%eax a2: 88 10 mov %dl,(%eax) a4: 8b 45 08 mov 0x8(%ebp),%eax a7: 8a 00 mov (%eax),%al a9: 84 c0 test %al,%al ab: 0f 95 c0 setne %al ae: ff 45 08 incl 0x8(%ebp) b1: ff 45 0c incl 0xc(%ebp) b4: 84 c0 test %al,%al b6: 75 e2 jne 9a <strcpy+0xd> ; return os; b8: 8b 45 fc mov -0x4(%ebp),%eax } bb: c9 leave bc: c3 ret 000000bd <strcmp>: int strcmp(const char *p, const char *q) { bd: 55 push %ebp be: 89 e5 mov %esp,%ebp while(*p && *p == *q) c0: eb 06 jmp c8 <strcmp+0xb> p++, q++; c2: ff 45 08 incl 0x8(%ebp) c5: ff 45 0c incl 0xc(%ebp) } int strcmp(const char *p, const char *q) { while(*p && *p == *q) c8: 8b 45 08 mov 0x8(%ebp),%eax cb: 8a 00 mov (%eax),%al cd: 84 c0 test %al,%al cf: 74 0e je df <strcmp+0x22> d1: 8b 45 08 mov 0x8(%ebp),%eax d4: 8a 10 mov (%eax),%dl d6: 8b 45 0c mov 0xc(%ebp),%eax d9: 8a 00 mov (%eax),%al db: 38 c2 cmp %al,%dl dd: 74 e3 je c2 <strcmp+0x5> p++, q++; return (uchar)*p - (uchar)*q; df: 8b 45 08 mov 0x8(%ebp),%eax e2: 8a 00 mov (%eax),%al e4: 0f b6 d0 movzbl %al,%edx e7: 8b 45 0c mov 0xc(%ebp),%eax ea: 8a 00 mov (%eax),%al ec: 0f b6 c0 movzbl %al,%eax ef: 89 d1 mov %edx,%ecx f1: 29 c1 sub %eax,%ecx f3: 89 c8 mov %ecx,%eax } f5: 5d pop %ebp f6: c3 ret 000000f7 <strlen>: uint strlen(char *s) { f7: 55 push %ebp f8: 89 e5 mov %esp,%ebp fa: 83 ec 10 sub $0x10,%esp int n; for(n = 0; s[n]; n++) fd: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) 104: eb 03 jmp 109 <strlen+0x12> 106: ff 45 fc incl -0x4(%ebp) 109: 8b 55 fc mov -0x4(%ebp),%edx 10c: 8b 45 08 mov 0x8(%ebp),%eax 10f: 01 d0 add %edx,%eax 111: 8a 00 mov (%eax),%al 113: 84 c0 test %al,%al 115: 75 ef jne 106 <strlen+0xf> ; return n; 117: 8b 45 fc mov -0x4(%ebp),%eax } 11a: c9 leave 11b: c3 ret 0000011c <memset>: void* memset(void *dst, int c, uint n) { 11c: 55 push %ebp 11d: 89 e5 mov %esp,%ebp 11f: 83 ec 0c sub $0xc,%esp stosb(dst, c, n); 122: 8b 45 10 mov 0x10(%ebp),%eax 125: 89 44 24 08 mov %eax,0x8(%esp) 129: 8b 45 0c mov 0xc(%ebp),%eax 12c: 89 44 24 04 mov %eax,0x4(%esp) 130: 8b 45 08 mov 0x8(%ebp),%eax 133: 89 04 24 mov %eax,(%esp) 136: e8 2d ff ff ff call 68 <stosb> return dst; 13b: 8b 45 08 mov 0x8(%ebp),%eax } 13e: c9 leave 13f: c3 ret 00000140 <strchr>: char* strchr(const char *s, char c) { 140: 55 push %ebp 141: 89 e5 mov %esp,%ebp 143: 83 ec 04 sub $0x4,%esp 146: 8b 45 0c mov 0xc(%ebp),%eax 149: 88 45 fc mov %al,-0x4(%ebp) for(; *s; s++) 14c: eb 12 jmp 160 <strchr+0x20> if(*s == c) 14e: 8b 45 08 mov 0x8(%ebp),%eax 151: 8a 00 mov (%eax),%al 153: 3a 45 fc cmp -0x4(%ebp),%al 156: 75 05 jne 15d <strchr+0x1d> return (char*)s; 158: 8b 45 08 mov 0x8(%ebp),%eax 15b: eb 11 jmp 16e <strchr+0x2e> } char* strchr(const char *s, char c) { for(; *s; s++) 15d: ff 45 08 incl 0x8(%ebp) 160: 8b 45 08 mov 0x8(%ebp),%eax 163: 8a 00 mov (%eax),%al 165: 84 c0 test %al,%al 167: 75 e5 jne 14e <strchr+0xe> if(*s == c) return (char*)s; return 0; 169: b8 00 00 00 00 mov $0x0,%eax } 16e: c9 leave 16f: c3 ret 00000170 <gets>: char* gets(char *buf, int max) { 170: 55 push %ebp 171: 89 e5 mov %esp,%ebp 173: 83 ec 28 sub $0x28,%esp int i, cc; char c; for(i=0; i+1 < max; ){ 176: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) 17d: eb 42 jmp 1c1 <gets+0x51> cc = read(0, &c, 1); 17f: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 186: 00 187: 8d 45 ef lea -0x11(%ebp),%eax 18a: 89 44 24 04 mov %eax,0x4(%esp) 18e: c7 04 24 00 00 00 00 movl $0x0,(%esp) 195: e8 32 01 00 00 call 2cc <read> 19a: 89 45 f0 mov %eax,-0x10(%ebp) if(cc < 1) 19d: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 1a1: 7e 29 jle 1cc <gets+0x5c> break; buf[i++] = c; 1a3: 8b 55 f4 mov -0xc(%ebp),%edx 1a6: 8b 45 08 mov 0x8(%ebp),%eax 1a9: 01 c2 add %eax,%edx 1ab: 8a 45 ef mov -0x11(%ebp),%al 1ae: 88 02 mov %al,(%edx) 1b0: ff 45 f4 incl -0xc(%ebp) if(c == '\n' || c == '\r') 1b3: 8a 45 ef mov -0x11(%ebp),%al 1b6: 3c 0a cmp $0xa,%al 1b8: 74 13 je 1cd <gets+0x5d> 1ba: 8a 45 ef mov -0x11(%ebp),%al 1bd: 3c 0d cmp $0xd,%al 1bf: 74 0c je 1cd <gets+0x5d> gets(char *buf, int max) { int i, cc; char c; for(i=0; i+1 < max; ){ 1c1: 8b 45 f4 mov -0xc(%ebp),%eax 1c4: 40 inc %eax 1c5: 3b 45 0c cmp 0xc(%ebp),%eax 1c8: 7c b5 jl 17f <gets+0xf> 1ca: eb 01 jmp 1cd <gets+0x5d> cc = read(0, &c, 1); if(cc < 1) break; 1cc: 90 nop buf[i++] = c; if(c == '\n' || c == '\r') break; } buf[i] = '\0'; 1cd: 8b 55 f4 mov -0xc(%ebp),%edx 1d0: 8b 45 08 mov 0x8(%ebp),%eax 1d3: 01 d0 add %edx,%eax 1d5: c6 00 00 movb $0x0,(%eax) return buf; 1d8: 8b 45 08 mov 0x8(%ebp),%eax } 1db: c9 leave 1dc: c3 ret 000001dd <stat>: int stat(char *n, struct stat *st) { 1dd: 55 push %ebp 1de: 89 e5 mov %esp,%ebp 1e0: 83 ec 28 sub $0x28,%esp int fd; int r; fd = open(n, O_RDONLY); 1e3: c7 44 24 04 00 00 00 movl $0x0,0x4(%esp) 1ea: 00 1eb: 8b 45 08 mov 0x8(%ebp),%eax 1ee: 89 04 24 mov %eax,(%esp) 1f1: e8 fe 00 00 00 call 2f4 <open> 1f6: 89 45 f4 mov %eax,-0xc(%ebp) if(fd < 0) 1f9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 1fd: 79 07 jns 206 <stat+0x29> return -1; 1ff: b8 ff ff ff ff mov $0xffffffff,%eax 204: eb 23 jmp 229 <stat+0x4c> r = fstat(fd, st); 206: 8b 45 0c mov 0xc(%ebp),%eax 209: 89 44 24 04 mov %eax,0x4(%esp) 20d: 8b 45 f4 mov -0xc(%ebp),%eax 210: 89 04 24 mov %eax,(%esp) 213: e8 f4 00 00 00 call 30c <fstat> 218: 89 45 f0 mov %eax,-0x10(%ebp) close(fd); 21b: 8b 45 f4 mov -0xc(%ebp),%eax 21e: 89 04 24 mov %eax,(%esp) 221: e8 b6 00 00 00 call 2dc <close> return r; 226: 8b 45 f0 mov -0x10(%ebp),%eax } 229: c9 leave 22a: c3 ret 0000022b <atoi>: int atoi(const char *s) { 22b: 55 push %ebp 22c: 89 e5 mov %esp,%ebp 22e: 83 ec 10 sub $0x10,%esp int n; n = 0; 231: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%ebp) while('0' <= *s && *s <= '9') 238: eb 21 jmp 25b <atoi+0x30> n = n*10 + *s++ - '0'; 23a: 8b 55 fc mov -0x4(%ebp),%edx 23d: 89 d0 mov %edx,%eax 23f: c1 e0 02 shl $0x2,%eax 242: 01 d0 add %edx,%eax 244: d1 e0 shl %eax 246: 89 c2 mov %eax,%edx 248: 8b 45 08 mov 0x8(%ebp),%eax 24b: 8a 00 mov (%eax),%al 24d: 0f be c0 movsbl %al,%eax 250: 01 d0 add %edx,%eax 252: 83 e8 30 sub $0x30,%eax 255: 89 45 fc mov %eax,-0x4(%ebp) 258: ff 45 08 incl 0x8(%ebp) atoi(const char *s) { int n; n = 0; while('0' <= *s && *s <= '9') 25b: 8b 45 08 mov 0x8(%ebp),%eax 25e: 8a 00 mov (%eax),%al 260: 3c 2f cmp $0x2f,%al 262: 7e 09 jle 26d <atoi+0x42> 264: 8b 45 08 mov 0x8(%ebp),%eax 267: 8a 00 mov (%eax),%al 269: 3c 39 cmp $0x39,%al 26b: 7e cd jle 23a <atoi+0xf> n = n*10 + *s++ - '0'; return n; 26d: 8b 45 fc mov -0x4(%ebp),%eax } 270: c9 leave 271: c3 ret 00000272 <memmove>: void* memmove(void *vdst, void *vsrc, int n) { 272: 55 push %ebp 273: 89 e5 mov %esp,%ebp 275: 83 ec 10 sub $0x10,%esp char *dst, *src; dst = vdst; 278: 8b 45 08 mov 0x8(%ebp),%eax 27b: 89 45 fc mov %eax,-0x4(%ebp) src = vsrc; 27e: 8b 45 0c mov 0xc(%ebp),%eax 281: 89 45 f8 mov %eax,-0x8(%ebp) while(n-- > 0) 284: eb 10 jmp 296 <memmove+0x24> *dst++ = *src++; 286: 8b 45 f8 mov -0x8(%ebp),%eax 289: 8a 10 mov (%eax),%dl 28b: 8b 45 fc mov -0x4(%ebp),%eax 28e: 88 10 mov %dl,(%eax) 290: ff 45 fc incl -0x4(%ebp) 293: ff 45 f8 incl -0x8(%ebp) { char *dst, *src; dst = vdst; src = vsrc; while(n-- > 0) 296: 83 7d 10 00 cmpl $0x0,0x10(%ebp) 29a: 0f 9f c0 setg %al 29d: ff 4d 10 decl 0x10(%ebp) 2a0: 84 c0 test %al,%al 2a2: 75 e2 jne 286 <memmove+0x14> *dst++ = *src++; return vdst; 2a4: 8b 45 08 mov 0x8(%ebp),%eax } 2a7: c9 leave 2a8: c3 ret 2a9: 66 90 xchg %ax,%ax 2ab: 90 nop 000002ac <fork>: name: \ movl $SYS_ ## name, %eax; \ int $T_SYSCALL; \ ret SYSCALL(fork) 2ac: b8 01 00 00 00 mov $0x1,%eax 2b1: cd 40 int $0x40 2b3: c3 ret 000002b4 <exit>: SYSCALL(exit) 2b4: b8 02 00 00 00 mov $0x2,%eax 2b9: cd 40 int $0x40 2bb: c3 ret 000002bc <wait>: SYSCALL(wait) 2bc: b8 03 00 00 00 mov $0x3,%eax 2c1: cd 40 int $0x40 2c3: c3 ret 000002c4 <pipe>: SYSCALL(pipe) 2c4: b8 04 00 00 00 mov $0x4,%eax 2c9: cd 40 int $0x40 2cb: c3 ret 000002cc <read>: SYSCALL(read) 2cc: b8 05 00 00 00 mov $0x5,%eax 2d1: cd 40 int $0x40 2d3: c3 ret 000002d4 <write>: SYSCALL(write) 2d4: b8 10 00 00 00 mov $0x10,%eax 2d9: cd 40 int $0x40 2db: c3 ret 000002dc <close>: SYSCALL(close) 2dc: b8 15 00 00 00 mov $0x15,%eax 2e1: cd 40 int $0x40 2e3: c3 ret 000002e4 <kill>: SYSCALL(kill) 2e4: b8 06 00 00 00 mov $0x6,%eax 2e9: cd 40 int $0x40 2eb: c3 ret 000002ec <exec>: SYSCALL(exec) 2ec: b8 07 00 00 00 mov $0x7,%eax 2f1: cd 40 int $0x40 2f3: c3 ret 000002f4 <open>: SYSCALL(open) 2f4: b8 0f 00 00 00 mov $0xf,%eax 2f9: cd 40 int $0x40 2fb: c3 ret 000002fc <mknod>: SYSCALL(mknod) 2fc: b8 11 00 00 00 mov $0x11,%eax 301: cd 40 int $0x40 303: c3 ret 00000304 <unlink>: SYSCALL(unlink) 304: b8 12 00 00 00 mov $0x12,%eax 309: cd 40 int $0x40 30b: c3 ret 0000030c <fstat>: SYSCALL(fstat) 30c: b8 08 00 00 00 mov $0x8,%eax 311: cd 40 int $0x40 313: c3 ret 00000314 <link>: SYSCALL(link) 314: b8 13 00 00 00 mov $0x13,%eax 319: cd 40 int $0x40 31b: c3 ret 0000031c <mkdir>: SYSCALL(mkdir) 31c: b8 14 00 00 00 mov $0x14,%eax 321: cd 40 int $0x40 323: c3 ret 00000324 <chdir>: SYSCALL(chdir) 324: b8 09 00 00 00 mov $0x9,%eax 329: cd 40 int $0x40 32b: c3 ret 0000032c <dup>: SYSCALL(dup) 32c: b8 0a 00 00 00 mov $0xa,%eax 331: cd 40 int $0x40 333: c3 ret 00000334 <getpid>: SYSCALL(getpid) 334: b8 0b 00 00 00 mov $0xb,%eax 339: cd 40 int $0x40 33b: c3 ret 0000033c <sbrk>: SYSCALL(sbrk) 33c: b8 0c 00 00 00 mov $0xc,%eax 341: cd 40 int $0x40 343: c3 ret 00000344 <sleep>: SYSCALL(sleep) 344: b8 0d 00 00 00 mov $0xd,%eax 349: cd 40 int $0x40 34b: c3 ret 0000034c <uptime>: SYSCALL(uptime) 34c: b8 0e 00 00 00 mov $0xe,%eax 351: cd 40 int $0x40 353: c3 ret 00000354 <getppid>: SYSCALL(getppid) // USER DEFINED SYS CALL 354: b8 16 00 00 00 mov $0x16,%eax 359: cd 40 int $0x40 35b: c3 ret 0000035c <icount>: SYSCALL(icount) // USER DEFINED SYS CALL 35c: b8 17 00 00 00 mov $0x17,%eax 361: cd 40 int $0x40 363: c3 ret 00000364 <signal>: SYSCALL(signal) // USER DEFINED SYS CALL 364: b8 18 00 00 00 mov $0x18,%eax 369: cd 40 int $0x40 36b: c3 ret 0000036c <putc>: #include "stat.h" #include "user.h" static void putc(int fd, char c) { 36c: 55 push %ebp 36d: 89 e5 mov %esp,%ebp 36f: 83 ec 28 sub $0x28,%esp 372: 8b 45 0c mov 0xc(%ebp),%eax 375: 88 45 f4 mov %al,-0xc(%ebp) write(fd, &c, 1); 378: c7 44 24 08 01 00 00 movl $0x1,0x8(%esp) 37f: 00 380: 8d 45 f4 lea -0xc(%ebp),%eax 383: 89 44 24 04 mov %eax,0x4(%esp) 387: 8b 45 08 mov 0x8(%ebp),%eax 38a: 89 04 24 mov %eax,(%esp) 38d: e8 42 ff ff ff call 2d4 <write> } 392: c9 leave 393: c3 ret 00000394 <printint>: static void printint(int fd, int xx, int base, int sgn) { 394: 55 push %ebp 395: 89 e5 mov %esp,%ebp 397: 83 ec 48 sub $0x48,%esp static char digits[] = "0123456789ABCDEF"; char buf[16]; int i, neg; uint x; neg = 0; 39a: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) if(sgn && xx < 0){ 3a1: 83 7d 14 00 cmpl $0x0,0x14(%ebp) 3a5: 74 17 je 3be <printint+0x2a> 3a7: 83 7d 0c 00 cmpl $0x0,0xc(%ebp) 3ab: 79 11 jns 3be <printint+0x2a> neg = 1; 3ad: c7 45 f0 01 00 00 00 movl $0x1,-0x10(%ebp) x = -xx; 3b4: 8b 45 0c mov 0xc(%ebp),%eax 3b7: f7 d8 neg %eax 3b9: 89 45 ec mov %eax,-0x14(%ebp) 3bc: eb 06 jmp 3c4 <printint+0x30> } else { x = xx; 3be: 8b 45 0c mov 0xc(%ebp),%eax 3c1: 89 45 ec mov %eax,-0x14(%ebp) } i = 0; 3c4: c7 45 f4 00 00 00 00 movl $0x0,-0xc(%ebp) do{ buf[i++] = digits[x % base]; 3cb: 8b 4d 10 mov 0x10(%ebp),%ecx 3ce: 8b 45 ec mov -0x14(%ebp),%eax 3d1: ba 00 00 00 00 mov $0x0,%edx 3d6: f7 f1 div %ecx 3d8: 89 d0 mov %edx,%eax 3da: 8a 80 64 0a 00 00 mov 0xa64(%eax),%al 3e0: 8d 4d dc lea -0x24(%ebp),%ecx 3e3: 8b 55 f4 mov -0xc(%ebp),%edx 3e6: 01 ca add %ecx,%edx 3e8: 88 02 mov %al,(%edx) 3ea: ff 45 f4 incl -0xc(%ebp) }while((x /= base) != 0); 3ed: 8b 55 10 mov 0x10(%ebp),%edx 3f0: 89 55 d4 mov %edx,-0x2c(%ebp) 3f3: 8b 45 ec mov -0x14(%ebp),%eax 3f6: ba 00 00 00 00 mov $0x0,%edx 3fb: f7 75 d4 divl -0x2c(%ebp) 3fe: 89 45 ec mov %eax,-0x14(%ebp) 401: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 405: 75 c4 jne 3cb <printint+0x37> if(neg) 407: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 40b: 74 2c je 439 <printint+0xa5> buf[i++] = '-'; 40d: 8d 55 dc lea -0x24(%ebp),%edx 410: 8b 45 f4 mov -0xc(%ebp),%eax 413: 01 d0 add %edx,%eax 415: c6 00 2d movb $0x2d,(%eax) 418: ff 45 f4 incl -0xc(%ebp) while(--i >= 0) 41b: eb 1c jmp 439 <printint+0xa5> putc(fd, buf[i]); 41d: 8d 55 dc lea -0x24(%ebp),%edx 420: 8b 45 f4 mov -0xc(%ebp),%eax 423: 01 d0 add %edx,%eax 425: 8a 00 mov (%eax),%al 427: 0f be c0 movsbl %al,%eax 42a: 89 44 24 04 mov %eax,0x4(%esp) 42e: 8b 45 08 mov 0x8(%ebp),%eax 431: 89 04 24 mov %eax,(%esp) 434: e8 33 ff ff ff call 36c <putc> buf[i++] = digits[x % base]; }while((x /= base) != 0); if(neg) buf[i++] = '-'; while(--i >= 0) 439: ff 4d f4 decl -0xc(%ebp) 43c: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 440: 79 db jns 41d <printint+0x89> putc(fd, buf[i]); } 442: c9 leave 443: c3 ret 00000444 <printf>: // Print to the given fd. Only understands %d, %x, %p, %s. void printf(int fd, char *fmt, ...) { 444: 55 push %ebp 445: 89 e5 mov %esp,%ebp 447: 83 ec 38 sub $0x38,%esp char *s; int c, i, state; uint *ap; state = 0; 44a: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) ap = (uint*)(void*)&fmt + 1; 451: 8d 45 0c lea 0xc(%ebp),%eax 454: 83 c0 04 add $0x4,%eax 457: 89 45 e8 mov %eax,-0x18(%ebp) for(i = 0; fmt[i]; i++){ 45a: c7 45 f0 00 00 00 00 movl $0x0,-0x10(%ebp) 461: e9 78 01 00 00 jmp 5de <printf+0x19a> c = fmt[i] & 0xff; 466: 8b 55 0c mov 0xc(%ebp),%edx 469: 8b 45 f0 mov -0x10(%ebp),%eax 46c: 01 d0 add %edx,%eax 46e: 8a 00 mov (%eax),%al 470: 0f be c0 movsbl %al,%eax 473: 25 ff 00 00 00 and $0xff,%eax 478: 89 45 e4 mov %eax,-0x1c(%ebp) if(state == 0){ 47b: 83 7d ec 00 cmpl $0x0,-0x14(%ebp) 47f: 75 2c jne 4ad <printf+0x69> if(c == '%'){ 481: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 485: 75 0c jne 493 <printf+0x4f> state = '%'; 487: c7 45 ec 25 00 00 00 movl $0x25,-0x14(%ebp) 48e: e9 48 01 00 00 jmp 5db <printf+0x197> } else { putc(fd, c); 493: 8b 45 e4 mov -0x1c(%ebp),%eax 496: 0f be c0 movsbl %al,%eax 499: 89 44 24 04 mov %eax,0x4(%esp) 49d: 8b 45 08 mov 0x8(%ebp),%eax 4a0: 89 04 24 mov %eax,(%esp) 4a3: e8 c4 fe ff ff call 36c <putc> 4a8: e9 2e 01 00 00 jmp 5db <printf+0x197> } } else if(state == '%'){ 4ad: 83 7d ec 25 cmpl $0x25,-0x14(%ebp) 4b1: 0f 85 24 01 00 00 jne 5db <printf+0x197> if(c == 'd'){ 4b7: 83 7d e4 64 cmpl $0x64,-0x1c(%ebp) 4bb: 75 2d jne 4ea <printf+0xa6> printint(fd, *ap, 10, 1); 4bd: 8b 45 e8 mov -0x18(%ebp),%eax 4c0: 8b 00 mov (%eax),%eax 4c2: c7 44 24 0c 01 00 00 movl $0x1,0xc(%esp) 4c9: 00 4ca: c7 44 24 08 0a 00 00 movl $0xa,0x8(%esp) 4d1: 00 4d2: 89 44 24 04 mov %eax,0x4(%esp) 4d6: 8b 45 08 mov 0x8(%ebp),%eax 4d9: 89 04 24 mov %eax,(%esp) 4dc: e8 b3 fe ff ff call 394 <printint> ap++; 4e1: 83 45 e8 04 addl $0x4,-0x18(%ebp) 4e5: e9 ea 00 00 00 jmp 5d4 <printf+0x190> } else if(c == 'x' || c == 'p'){ 4ea: 83 7d e4 78 cmpl $0x78,-0x1c(%ebp) 4ee: 74 06 je 4f6 <printf+0xb2> 4f0: 83 7d e4 70 cmpl $0x70,-0x1c(%ebp) 4f4: 75 2d jne 523 <printf+0xdf> printint(fd, *ap, 16, 0); 4f6: 8b 45 e8 mov -0x18(%ebp),%eax 4f9: 8b 00 mov (%eax),%eax 4fb: c7 44 24 0c 00 00 00 movl $0x0,0xc(%esp) 502: 00 503: c7 44 24 08 10 00 00 movl $0x10,0x8(%esp) 50a: 00 50b: 89 44 24 04 mov %eax,0x4(%esp) 50f: 8b 45 08 mov 0x8(%ebp),%eax 512: 89 04 24 mov %eax,(%esp) 515: e8 7a fe ff ff call 394 <printint> ap++; 51a: 83 45 e8 04 addl $0x4,-0x18(%ebp) 51e: e9 b1 00 00 00 jmp 5d4 <printf+0x190> } else if(c == 's'){ 523: 83 7d e4 73 cmpl $0x73,-0x1c(%ebp) 527: 75 43 jne 56c <printf+0x128> s = (char*)*ap; 529: 8b 45 e8 mov -0x18(%ebp),%eax 52c: 8b 00 mov (%eax),%eax 52e: 89 45 f4 mov %eax,-0xc(%ebp) ap++; 531: 83 45 e8 04 addl $0x4,-0x18(%ebp) if(s == 0) 535: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 539: 75 25 jne 560 <printf+0x11c> s = "(null)"; 53b: c7 45 f4 1f 08 00 00 movl $0x81f,-0xc(%ebp) while(*s != 0){ 542: eb 1c jmp 560 <printf+0x11c> putc(fd, *s); 544: 8b 45 f4 mov -0xc(%ebp),%eax 547: 8a 00 mov (%eax),%al 549: 0f be c0 movsbl %al,%eax 54c: 89 44 24 04 mov %eax,0x4(%esp) 550: 8b 45 08 mov 0x8(%ebp),%eax 553: 89 04 24 mov %eax,(%esp) 556: e8 11 fe ff ff call 36c <putc> s++; 55b: ff 45 f4 incl -0xc(%ebp) 55e: eb 01 jmp 561 <printf+0x11d> } else if(c == 's'){ s = (char*)*ap; ap++; if(s == 0) s = "(null)"; while(*s != 0){ 560: 90 nop 561: 8b 45 f4 mov -0xc(%ebp),%eax 564: 8a 00 mov (%eax),%al 566: 84 c0 test %al,%al 568: 75 da jne 544 <printf+0x100> 56a: eb 68 jmp 5d4 <printf+0x190> putc(fd, *s); s++; } } else if(c == 'c'){ 56c: 83 7d e4 63 cmpl $0x63,-0x1c(%ebp) 570: 75 1d jne 58f <printf+0x14b> putc(fd, *ap); 572: 8b 45 e8 mov -0x18(%ebp),%eax 575: 8b 00 mov (%eax),%eax 577: 0f be c0 movsbl %al,%eax 57a: 89 44 24 04 mov %eax,0x4(%esp) 57e: 8b 45 08 mov 0x8(%ebp),%eax 581: 89 04 24 mov %eax,(%esp) 584: e8 e3 fd ff ff call 36c <putc> ap++; 589: 83 45 e8 04 addl $0x4,-0x18(%ebp) 58d: eb 45 jmp 5d4 <printf+0x190> } else if(c == '%'){ 58f: 83 7d e4 25 cmpl $0x25,-0x1c(%ebp) 593: 75 17 jne 5ac <printf+0x168> putc(fd, c); 595: 8b 45 e4 mov -0x1c(%ebp),%eax 598: 0f be c0 movsbl %al,%eax 59b: 89 44 24 04 mov %eax,0x4(%esp) 59f: 8b 45 08 mov 0x8(%ebp),%eax 5a2: 89 04 24 mov %eax,(%esp) 5a5: e8 c2 fd ff ff call 36c <putc> 5aa: eb 28 jmp 5d4 <printf+0x190> } else { // Unknown % sequence. Print it to draw attention. putc(fd, '%'); 5ac: c7 44 24 04 25 00 00 movl $0x25,0x4(%esp) 5b3: 00 5b4: 8b 45 08 mov 0x8(%ebp),%eax 5b7: 89 04 24 mov %eax,(%esp) 5ba: e8 ad fd ff ff call 36c <putc> putc(fd, c); 5bf: 8b 45 e4 mov -0x1c(%ebp),%eax 5c2: 0f be c0 movsbl %al,%eax 5c5: 89 44 24 04 mov %eax,0x4(%esp) 5c9: 8b 45 08 mov 0x8(%ebp),%eax 5cc: 89 04 24 mov %eax,(%esp) 5cf: e8 98 fd ff ff call 36c <putc> } state = 0; 5d4: c7 45 ec 00 00 00 00 movl $0x0,-0x14(%ebp) int c, i, state; uint *ap; state = 0; ap = (uint*)(void*)&fmt + 1; for(i = 0; fmt[i]; i++){ 5db: ff 45 f0 incl -0x10(%ebp) 5de: 8b 55 0c mov 0xc(%ebp),%edx 5e1: 8b 45 f0 mov -0x10(%ebp),%eax 5e4: 01 d0 add %edx,%eax 5e6: 8a 00 mov (%eax),%al 5e8: 84 c0 test %al,%al 5ea: 0f 85 76 fe ff ff jne 466 <printf+0x22> putc(fd, c); } state = 0; } } } 5f0: c9 leave 5f1: c3 ret 5f2: 66 90 xchg %ax,%ax 000005f4 <free>: static Header base; static Header *freep; void free(void *ap) { 5f4: 55 push %ebp 5f5: 89 e5 mov %esp,%ebp 5f7: 83 ec 10 sub $0x10,%esp Header *bp, *p; bp = (Header*)ap - 1; 5fa: 8b 45 08 mov 0x8(%ebp),%eax 5fd: 83 e8 08 sub $0x8,%eax 600: 89 45 f8 mov %eax,-0x8(%ebp) for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 603: a1 80 0a 00 00 mov 0xa80,%eax 608: 89 45 fc mov %eax,-0x4(%ebp) 60b: eb 24 jmp 631 <free+0x3d> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) 60d: 8b 45 fc mov -0x4(%ebp),%eax 610: 8b 00 mov (%eax),%eax 612: 3b 45 fc cmp -0x4(%ebp),%eax 615: 77 12 ja 629 <free+0x35> 617: 8b 45 f8 mov -0x8(%ebp),%eax 61a: 3b 45 fc cmp -0x4(%ebp),%eax 61d: 77 24 ja 643 <free+0x4f> 61f: 8b 45 fc mov -0x4(%ebp),%eax 622: 8b 00 mov (%eax),%eax 624: 3b 45 f8 cmp -0x8(%ebp),%eax 627: 77 1a ja 643 <free+0x4f> free(void *ap) { Header *bp, *p; bp = (Header*)ap - 1; for(p = freep; !(bp > p && bp < p->s.ptr); p = p->s.ptr) 629: 8b 45 fc mov -0x4(%ebp),%eax 62c: 8b 00 mov (%eax),%eax 62e: 89 45 fc mov %eax,-0x4(%ebp) 631: 8b 45 f8 mov -0x8(%ebp),%eax 634: 3b 45 fc cmp -0x4(%ebp),%eax 637: 76 d4 jbe 60d <free+0x19> 639: 8b 45 fc mov -0x4(%ebp),%eax 63c: 8b 00 mov (%eax),%eax 63e: 3b 45 f8 cmp -0x8(%ebp),%eax 641: 76 ca jbe 60d <free+0x19> if(p >= p->s.ptr && (bp > p || bp < p->s.ptr)) break; if(bp + bp->s.size == p->s.ptr){ 643: 8b 45 f8 mov -0x8(%ebp),%eax 646: 8b 40 04 mov 0x4(%eax),%eax 649: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 650: 8b 45 f8 mov -0x8(%ebp),%eax 653: 01 c2 add %eax,%edx 655: 8b 45 fc mov -0x4(%ebp),%eax 658: 8b 00 mov (%eax),%eax 65a: 39 c2 cmp %eax,%edx 65c: 75 24 jne 682 <free+0x8e> bp->s.size += p->s.ptr->s.size; 65e: 8b 45 f8 mov -0x8(%ebp),%eax 661: 8b 50 04 mov 0x4(%eax),%edx 664: 8b 45 fc mov -0x4(%ebp),%eax 667: 8b 00 mov (%eax),%eax 669: 8b 40 04 mov 0x4(%eax),%eax 66c: 01 c2 add %eax,%edx 66e: 8b 45 f8 mov -0x8(%ebp),%eax 671: 89 50 04 mov %edx,0x4(%eax) bp->s.ptr = p->s.ptr->s.ptr; 674: 8b 45 fc mov -0x4(%ebp),%eax 677: 8b 00 mov (%eax),%eax 679: 8b 10 mov (%eax),%edx 67b: 8b 45 f8 mov -0x8(%ebp),%eax 67e: 89 10 mov %edx,(%eax) 680: eb 0a jmp 68c <free+0x98> } else bp->s.ptr = p->s.ptr; 682: 8b 45 fc mov -0x4(%ebp),%eax 685: 8b 10 mov (%eax),%edx 687: 8b 45 f8 mov -0x8(%ebp),%eax 68a: 89 10 mov %edx,(%eax) if(p + p->s.size == bp){ 68c: 8b 45 fc mov -0x4(%ebp),%eax 68f: 8b 40 04 mov 0x4(%eax),%eax 692: 8d 14 c5 00 00 00 00 lea 0x0(,%eax,8),%edx 699: 8b 45 fc mov -0x4(%ebp),%eax 69c: 01 d0 add %edx,%eax 69e: 3b 45 f8 cmp -0x8(%ebp),%eax 6a1: 75 20 jne 6c3 <free+0xcf> p->s.size += bp->s.size; 6a3: 8b 45 fc mov -0x4(%ebp),%eax 6a6: 8b 50 04 mov 0x4(%eax),%edx 6a9: 8b 45 f8 mov -0x8(%ebp),%eax 6ac: 8b 40 04 mov 0x4(%eax),%eax 6af: 01 c2 add %eax,%edx 6b1: 8b 45 fc mov -0x4(%ebp),%eax 6b4: 89 50 04 mov %edx,0x4(%eax) p->s.ptr = bp->s.ptr; 6b7: 8b 45 f8 mov -0x8(%ebp),%eax 6ba: 8b 10 mov (%eax),%edx 6bc: 8b 45 fc mov -0x4(%ebp),%eax 6bf: 89 10 mov %edx,(%eax) 6c1: eb 08 jmp 6cb <free+0xd7> } else p->s.ptr = bp; 6c3: 8b 45 fc mov -0x4(%ebp),%eax 6c6: 8b 55 f8 mov -0x8(%ebp),%edx 6c9: 89 10 mov %edx,(%eax) freep = p; 6cb: 8b 45 fc mov -0x4(%ebp),%eax 6ce: a3 80 0a 00 00 mov %eax,0xa80 } 6d3: c9 leave 6d4: c3 ret 000006d5 <morecore>: static Header* morecore(uint nu) { 6d5: 55 push %ebp 6d6: 89 e5 mov %esp,%ebp 6d8: 83 ec 28 sub $0x28,%esp char *p; Header *hp; if(nu < 4096) 6db: 81 7d 08 ff 0f 00 00 cmpl $0xfff,0x8(%ebp) 6e2: 77 07 ja 6eb <morecore+0x16> nu = 4096; 6e4: c7 45 08 00 10 00 00 movl $0x1000,0x8(%ebp) p = sbrk(nu * sizeof(Header)); 6eb: 8b 45 08 mov 0x8(%ebp),%eax 6ee: c1 e0 03 shl $0x3,%eax 6f1: 89 04 24 mov %eax,(%esp) 6f4: e8 43 fc ff ff call 33c <sbrk> 6f9: 89 45 f4 mov %eax,-0xc(%ebp) if(p == (char*)-1) 6fc: 83 7d f4 ff cmpl $0xffffffff,-0xc(%ebp) 700: 75 07 jne 709 <morecore+0x34> return 0; 702: b8 00 00 00 00 mov $0x0,%eax 707: eb 22 jmp 72b <morecore+0x56> hp = (Header*)p; 709: 8b 45 f4 mov -0xc(%ebp),%eax 70c: 89 45 f0 mov %eax,-0x10(%ebp) hp->s.size = nu; 70f: 8b 45 f0 mov -0x10(%ebp),%eax 712: 8b 55 08 mov 0x8(%ebp),%edx 715: 89 50 04 mov %edx,0x4(%eax) free((void*)(hp + 1)); 718: 8b 45 f0 mov -0x10(%ebp),%eax 71b: 83 c0 08 add $0x8,%eax 71e: 89 04 24 mov %eax,(%esp) 721: e8 ce fe ff ff call 5f4 <free> return freep; 726: a1 80 0a 00 00 mov 0xa80,%eax } 72b: c9 leave 72c: c3 ret 0000072d <malloc>: void* malloc(uint nbytes) { 72d: 55 push %ebp 72e: 89 e5 mov %esp,%ebp 730: 83 ec 28 sub $0x28,%esp Header *p, *prevp; uint nunits; nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; 733: 8b 45 08 mov 0x8(%ebp),%eax 736: 83 c0 07 add $0x7,%eax 739: c1 e8 03 shr $0x3,%eax 73c: 40 inc %eax 73d: 89 45 ec mov %eax,-0x14(%ebp) if((prevp = freep) == 0){ 740: a1 80 0a 00 00 mov 0xa80,%eax 745: 89 45 f0 mov %eax,-0x10(%ebp) 748: 83 7d f0 00 cmpl $0x0,-0x10(%ebp) 74c: 75 23 jne 771 <malloc+0x44> base.s.ptr = freep = prevp = &base; 74e: c7 45 f0 78 0a 00 00 movl $0xa78,-0x10(%ebp) 755: 8b 45 f0 mov -0x10(%ebp),%eax 758: a3 80 0a 00 00 mov %eax,0xa80 75d: a1 80 0a 00 00 mov 0xa80,%eax 762: a3 78 0a 00 00 mov %eax,0xa78 base.s.size = 0; 767: c7 05 7c 0a 00 00 00 movl $0x0,0xa7c 76e: 00 00 00 } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 771: 8b 45 f0 mov -0x10(%ebp),%eax 774: 8b 00 mov (%eax),%eax 776: 89 45 f4 mov %eax,-0xc(%ebp) if(p->s.size >= nunits){ 779: 8b 45 f4 mov -0xc(%ebp),%eax 77c: 8b 40 04 mov 0x4(%eax),%eax 77f: 3b 45 ec cmp -0x14(%ebp),%eax 782: 72 4d jb 7d1 <malloc+0xa4> if(p->s.size == nunits) 784: 8b 45 f4 mov -0xc(%ebp),%eax 787: 8b 40 04 mov 0x4(%eax),%eax 78a: 3b 45 ec cmp -0x14(%ebp),%eax 78d: 75 0c jne 79b <malloc+0x6e> prevp->s.ptr = p->s.ptr; 78f: 8b 45 f4 mov -0xc(%ebp),%eax 792: 8b 10 mov (%eax),%edx 794: 8b 45 f0 mov -0x10(%ebp),%eax 797: 89 10 mov %edx,(%eax) 799: eb 26 jmp 7c1 <malloc+0x94> else { p->s.size -= nunits; 79b: 8b 45 f4 mov -0xc(%ebp),%eax 79e: 8b 40 04 mov 0x4(%eax),%eax 7a1: 89 c2 mov %eax,%edx 7a3: 2b 55 ec sub -0x14(%ebp),%edx 7a6: 8b 45 f4 mov -0xc(%ebp),%eax 7a9: 89 50 04 mov %edx,0x4(%eax) p += p->s.size; 7ac: 8b 45 f4 mov -0xc(%ebp),%eax 7af: 8b 40 04 mov 0x4(%eax),%eax 7b2: c1 e0 03 shl $0x3,%eax 7b5: 01 45 f4 add %eax,-0xc(%ebp) p->s.size = nunits; 7b8: 8b 45 f4 mov -0xc(%ebp),%eax 7bb: 8b 55 ec mov -0x14(%ebp),%edx 7be: 89 50 04 mov %edx,0x4(%eax) } freep = prevp; 7c1: 8b 45 f0 mov -0x10(%ebp),%eax 7c4: a3 80 0a 00 00 mov %eax,0xa80 return (void*)(p + 1); 7c9: 8b 45 f4 mov -0xc(%ebp),%eax 7cc: 83 c0 08 add $0x8,%eax 7cf: eb 38 jmp 809 <malloc+0xdc> } if(p == freep) 7d1: a1 80 0a 00 00 mov 0xa80,%eax 7d6: 39 45 f4 cmp %eax,-0xc(%ebp) 7d9: 75 1b jne 7f6 <malloc+0xc9> if((p = morecore(nunits)) == 0) 7db: 8b 45 ec mov -0x14(%ebp),%eax 7de: 89 04 24 mov %eax,(%esp) 7e1: e8 ef fe ff ff call 6d5 <morecore> 7e6: 89 45 f4 mov %eax,-0xc(%ebp) 7e9: 83 7d f4 00 cmpl $0x0,-0xc(%ebp) 7ed: 75 07 jne 7f6 <malloc+0xc9> return 0; 7ef: b8 00 00 00 00 mov $0x0,%eax 7f4: eb 13 jmp 809 <malloc+0xdc> nunits = (nbytes + sizeof(Header) - 1)/sizeof(Header) + 1; if((prevp = freep) == 0){ base.s.ptr = freep = prevp = &base; base.s.size = 0; } for(p = prevp->s.ptr; ; prevp = p, p = p->s.ptr){ 7f6: 8b 45 f4 mov -0xc(%ebp),%eax 7f9: 89 45 f0 mov %eax,-0x10(%ebp) 7fc: 8b 45 f4 mov -0xc(%ebp),%eax 7ff: 8b 00 mov (%eax),%eax 801: 89 45 f4 mov %eax,-0xc(%ebp) return (void*)(p + 1); } if(p == freep) if((p = morecore(nunits)) == 0) return 0; } 804: e9 70 ff ff ff jmp 779 <malloc+0x4c> } 809: c9 leave 80a: c3 ret
/* ************************************************************************************************************* */ /* */ /* GLIP-LIB */ /* OpenGL Image Processing LIBrary */ /* */ /* Author : R. Kerviche */ /* LICENSE : MIT License */ /* Website : glip-lib.net */ /* */ /* File : HdlTextureTools.cpp */ /* Original Date : August 18th 2012 */ /* */ /* Description : OpenGL Texture Handle and descriptors */ /* */ /* ************************************************************************************************************* */ /** * \file HdlTextureTools.cpp * \brief OpenGL Texture Handle Tools * \author R. KERVICHE * \date August 18th 2012 **/ #include <cstring> #include <algorithm> #include "Core/HdlTextureTools.hpp" #include "Core/Exception.hpp" using namespace Glip::CoreGL; GLIP_API const int HdlTextureFormatDescriptor::maxNumChannels = 4; GLIP_API const int HdlTextureFormatDescriptor::maxPixelSizeInBits = 128; GLIP_API const int HdlTextureFormatDescriptor::maxPixelSize = 16; #ifdef GLIP_USE_GL #define ALIAS_GL_COMPRESSED_RED GL_COMPRESSED_RED #define ALIAS_GL_COMPRESSED_ALPHA GL_COMPRESSED_ALPHA #define ALIAS_GL_COMPRESSED_LUMINANCE GL_COMPRESSED_LUMINANCE #define ALIAS_GL_COMPRESSED_INTENSITY GL_COMPRESSED_INTENSITY #define ALIAS_GL_COMPRESSED_RG GL_COMPRESSED_RG #define ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA GL_COMPRESSED_LUMINANCE_ALPHA #define ALIAS_GL_COMPRESSED_RGB GL_COMPRESSED_RGB #define ALIAS_GL_COMPRESSED_SRGB GL_COMPRESSED_SRGB #define ALIAS_GL_COMPRESSED_RGBA GL_COMPRESSED_RGBA #define ALIAS_GL_COMPRESSED_SRGB_ALPHA GL_COMPRESSED_SRGB_ALPHA #else #define ALIAS_GL_COMPRESSED_RED GL_NONE #define ALIAS_GL_COMPRESSED_ALPHA GL_NONE #define ALIAS_GL_COMPRESSED_LUMINANCE GL_NONE #define ALIAS_GL_COMPRESSED_INTENSITY GL_NONE #define ALIAS_GL_COMPRESSED_RG GL_NONE #define ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA GL_NONE #define ALIAS_GL_COMPRESSED_RGB GL_NONE #define ALIAS_GL_COMPRESSED_SRGB GL_NONE #define ALIAS_GL_COMPRESSED_RGBA GL_NONE #define ALIAS_GL_COMPRESSED_SRGB_ALPHA GL_NONE #endif // List of all the Mode accepted : const HdlTextureFormatDescriptor HdlTextureFormatDescriptorsList::textureFormatDescriptors[] = { {GL_RED, GL_RED, GL_RED, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_GREEN, GL_RED, GL_GREEN, ALIAS_GL_COMPRESSED_RED, 1, {GL_GREEN, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_BLUE, GL_RED, GL_BLUE, ALIAS_GL_COMPRESSED_RED, 1, {GL_BLUE, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R8, GL_RED, GL_R8, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_UNSIGNED_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R8I, GL_RED, GL_R8I, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R8UI, GL_RED, GL_R8UI, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_UNSIGNED_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R8_SNORM, GL_RED, GL_R8_SNORM, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_R16, GL_RED, GL_R16, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_UNSIGNED_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_R16I, GL_RED, GL_R16I, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R16UI, GL_RED, GL_R16UI, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_UNSIGNED_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_R16_SNORM, GL_RED, GL_R16_SNORM, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_R16F, GL_RED, GL_R16F, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_R32I, GL_RED, GL_R32I, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_INT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R32UI, GL_RED, GL_R32UI, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_UNSIGNED_INT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_R32F, GL_RED, GL_R32F, ALIAS_GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_ALPHA, GL_ALPHA, GL_ALPHA, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_ALPHA4, GL_ALPHA, GL_ALPHA4, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {4, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_ALPHA8, GL_ALPHA, GL_ALPHA8, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_UNSIGNED_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_ALPHA8_SNORM, GL_ALPHA, GL_ALPHA8_SNORM, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_ALPHA12, GL_ALPHA, GL_ALPHA12, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {12, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_ALPHA16, GL_ALPHA, GL_ALPHA16, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_UNSIGNED_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_ALPHA16F_ARB, GL_ALPHA, GL_ALPHA16F_ARB, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_ALPHA16_SNORM, GL_ALPHA, GL_ALPHA16_SNORM, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_ALPHA32F_ARB, GL_ALPHA, GL_ALPHA32F_ARB, ALIAS_GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, #endif {GL_LUMINANCE, GL_LUMINANCE, GL_LUMINANCE, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_LUMINANCE4, GL_LUMINANCE, GL_LUMINANCE4, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {4, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_LUMINANCE8, GL_LUMINANCE, GL_LUMINANCE8, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_UNSIGNED_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE8_SNORM, GL_LUMINANCE, GL_LUMINANCE8_SNORM, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE12, GL_LUMINANCE, GL_LUMINANCE12, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {12, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_LUMINANCE16, GL_LUMINANCE, GL_LUMINANCE16, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_UNSIGNED_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE16F_ARB, GL_LUMINANCE, GL_LUMINANCE16F_ARB, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_LUMINANCE16_SNORM, GL_LUMINANCE, GL_LUMINANCE16_SNORM, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE32F_ARB, GL_LUMINANCE, GL_LUMINANCE32F_ARB, ALIAS_GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_INTENSITY, GL_INTENSITY, GL_INTENSITY, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {-1, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_INTENSITY4, GL_INTENSITY, GL_INTENSITY4, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {4, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_INTENSITY8, GL_INTENSITY, GL_INTENSITY8, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_UNSIGNED_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_INTENSITY8_SNORM, GL_INTENSITY, GL_INTENSITY8_SNORM, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {8, 0, 0, 0}, {GL_BYTE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_INTENSITY12, GL_INTENSITY, GL_INTENSITY12, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {12, 0, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_INTENSITY16, GL_INTENSITY, GL_INTENSITY16, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_UNSIGNED_SHORT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_INTENSITY16F_ARB, GL_INTENSITY, GL_INTENSITY16F_ARB, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, {GL_INTENSITY16_SNORM, GL_INTENSITY, GL_INTENSITY16_SNORM, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {16, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_INTENSITY32F_ARB, GL_INTENSITY, GL_INTENSITY32F_ARB, ALIAS_GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {32, 0, 0, 0}, {GL_FLOAT, GL_NONE, GL_NONE, GL_NONE}, true, false, true}, #endif {GL_RG, GL_RG, GL_RG, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {-1, -1, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_RG8, GL_RG, GL_RG8, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_NONE, GL_NONE}, false, false, true}, {GL_RG8I, GL_RG, GL_RG8I, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_BYTE, GL_BYTE, GL_NONE, GL_NONE}, false, false, true}, {GL_RG8UI, GL_RG, GL_RG8UI, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_NONE, GL_NONE}, false, false, true}, {GL_RG8_SNORM, GL_RG, GL_RG8_SNORM, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_BYTE, GL_BYTE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_RG16, GL_RG, GL_RG16, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_RG16I, GL_RG, GL_RG16I, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_SHORT, GL_SHORT, GL_NONE, GL_NONE}, false, false, true}, {GL_RG16UI, GL_RG, GL_RG16UI, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_NONE, GL_NONE}, false, false, true}, {GL_RG16F, GL_RG, GL_RG16F, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_FLOAT, GL_FLOAT, GL_NONE, GL_NONE}, true, false, true}, #ifdef GLIP_USE_GL {GL_RG16_SNORM, GL_RG, GL_RG16_SNORM, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_SHORT, GL_SHORT, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_RG32I, GL_RG, GL_RG32I, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {32, 32, 0, 0}, {GL_INT, GL_INT, GL_NONE, GL_NONE}, false, false, true}, {GL_RG32UI, GL_RG, GL_RG32UI, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {32, 32, 0, 0}, {GL_UNSIGNED_INT, GL_UNSIGNED_INT, GL_NONE, GL_NONE}, false, false, true}, {GL_RG32F, GL_RG, GL_RG32F, ALIAS_GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {32, 32, 0, 0}, {GL_FLOAT, GL_FLOAT, GL_NONE, GL_NONE}, true, false, true}, {GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {-1, -1, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_LUMINANCE4_ALPHA4, GL_LUMINANCE_ALPHA, GL_LUMINANCE4_ALPHA4, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {4, 4, 0, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_LUMINANCE8_ALPHA8, GL_LUMINANCE_ALPHA, GL_LUMINANCE8_ALPHA8, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_BYTE, GL_BYTE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE8_ALPHA8_SNORM, GL_LUMINANCE_ALPHA, GL_LUMINANCE8_ALPHA8_SNORM, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {8, 8, 0, 0}, {GL_BYTE, GL_BYTE, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE16_ALPHA16, GL_LUMINANCE_ALPHA, GL_LUMINANCE16_ALPHA16, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {16, 16, 0, 0}, {GL_SHORT, GL_SHORT, GL_NONE, GL_NONE}, false, false, true}, {GL_LUMINANCE_ALPHA32F_ARB, GL_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA32F_ARB, ALIAS_GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {32, 32, 0, 0}, {GL_FLOAT, GL_FLOAT, GL_NONE, GL_NONE}, true, false, true}, #endif {GL_RGB, GL_RGB, GL_RGB, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_BGR, GL_BGR, GL_BGR, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_SRGB, GL_SRGB, GL_SRGB, ALIAS_GL_COMPRESSED_SRGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_RGB4, GL_RGB, GL_RGB4, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {4, 4, 4, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, #endif {GL_RGB8, GL_RGB, GL_RGB8, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {8, 8, 8, 0}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_NONE}, false, false, true}, {GL_RGB8I, GL_RGB, GL_RGB8I, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {8, 8, 8, 0}, {GL_BYTE, GL_BYTE, GL_BYTE, GL_NONE}, false, false, true}, {GL_RGB8UI, GL_RGB, GL_RGB8UI, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {8, 8, 8, 0}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_NONE}, false, false, true}, {GL_RGB8_SNORM, GL_RGB, GL_RGB8_SNORM, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {8, 8, 8, 0}, {GL_BYTE, GL_BYTE, GL_BYTE, GL_NONE}, false, false, true}, {GL_SRGB8, GL_RGB, GL_SRGB8, ALIAS_GL_COMPRESSED_SRGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {8, 8, 8, 0}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_RGB10, GL_RGB, GL_RGB10, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {10, 10, 10, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_RGB12, GL_RGB, GL_RGB12, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {12, 12, 12, 0}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_RGB16, GL_RGB, GL_RGB16, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {16, 16, 16, 0}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_NONE}, false, false, true}, #endif {GL_RGB16I, GL_RGB, GL_RGB16I, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {16, 16, 16, 0}, {GL_SHORT, GL_SHORT, GL_SHORT, GL_NONE}, false, false, true}, {GL_RGB16UI, GL_RGB, GL_RGB16UI, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {16, 16, 16, 0}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_RGB16_SNORM, GL_RGB, GL_RGB16_SNORM, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {16, 16, 16, 0}, {GL_SHORT, GL_SHORT, GL_SHORT, GL_NONE}, false, false, true}, #endif {GL_RGB16F, GL_RGB, GL_RGB16F, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {16, 16, 16, 0}, {GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_NONE}, true, false, true}, {GL_RGB32I, GL_RGB, GL_RGB32I, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {32, 32, 32, 0}, {GL_INT, GL_INT, GL_INT, GL_NONE}, false, false, true}, {GL_RGB32UI, GL_RGB, GL_RGB32UI, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {32, 32, 32, 0}, {GL_UNSIGNED_INT, GL_UNSIGNED_INT, GL_UNSIGNED_INT, GL_NONE}, false, false, true}, {GL_RGB32F, GL_RGB, GL_RGB32F, ALIAS_GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {32, 32, 32, 0}, {GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_NONE}, true, false, true}, {GL_RGBA, GL_RGBA, GL_RGBA, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #ifdef GLIP_USE_GL {GL_BGRA, GL_BGRA, GL_BGRA, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_BLUE, GL_GREEN, GL_RED, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_RGBA_SNORM, GL_RGBA, GL_RGBA_SNORM, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, {GL_SRGB_ALPHA, GL_RGBA, GL_SRGB_ALPHA, ALIAS_GL_COMPRESSED_SRGB_ALPHA,4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, true}, #endif {GL_RGBA4, GL_RGBA, GL_RGBA4, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {4, 4, 4, 4}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false}, {GL_RGBA8, GL_RGBA, GL_RGBA8, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {8, 8, 8, 8}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE}, false, false, true}, {GL_RGBA8I, GL_RGBA, GL_RGBA8I, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {8, 8, 8, 8}, {GL_BYTE, GL_BYTE, GL_BYTE, GL_BYTE}, false, false, true}, {GL_RGBA8UI, GL_RGBA, GL_RGBA8UI, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {8, 8, 8, 8}, {GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE, GL_UNSIGNED_BYTE}, false, false, true}, {GL_RGBA8_SNORM, GL_RGBA, GL_RGBA8_SNORM, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {8, 8, 8, 8}, {GL_BYTE, GL_BYTE, GL_BYTE, GL_BYTE}, false, false, true}, {GL_SRGB8_ALPHA8, GL_RGBA, GL_SRGB8_ALPHA8, ALIAS_GL_COMPRESSED_SRGB_ALPHA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {8, 8, 8, 8}, {GL_BYTE, GL_BYTE, GL_BYTE, GL_BYTE}, false, false, true}, #ifdef GLIP_USE_GL {GL_RGBA16, GL_RGBA, GL_RGBA16, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {16, 16, 16, 16}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT}, false, false, true}, #endif {GL_RGBA16I, GL_RGBA, GL_RGBA16I, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {16, 16, 16, 16}, {GL_SHORT, GL_SHORT, GL_SHORT, GL_SHORT}, false, false, true}, {GL_RGBA16UI, GL_RGBA, GL_RGBA16UI, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {16, 16, 16, 16}, {GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT, GL_UNSIGNED_SHORT}, false, false, true}, {GL_RGBA16F, GL_RGBA, GL_RGBA16F, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {16, 16, 16, 16}, {GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_FLOAT}, true, false, true}, #ifdef GLIP_USE_GL {GL_RGBA16_SNORM, GL_RGBA, GL_RGBA16_SNORM, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {16, 16, 16, 16}, {GL_SHORT, GL_SHORT, GL_SHORT, GL_SHORT}, false, false, true}, #endif {GL_RGBA32I, GL_RGBA, GL_RGBA32I, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {32, 32, 32, 32}, {GL_INT, GL_INT, GL_INT, GL_INT}, false, false, true}, {GL_RGBA32UI, GL_RGBA, GL_RGBA32UI, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {32, 32, 32, 32}, {GL_UNSIGNED_INT, GL_UNSIGNED_INT, GL_UNSIGNED_INT, GL_NONE}, false, false, true}, {GL_RGBA32F, GL_RGBA, GL_RGBA32F, ALIAS_GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {32, 32, 32, 32}, {GL_FLOAT, GL_FLOAT, GL_FLOAT, GL_FLOAT}, true, false, true}, #ifdef GLIP_USE_GL {GL_COMPRESSED_RED, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RED_RGTC1, GL_COMPRESSED_RED, GL_RED, GL_COMPRESSED_RED_RGTC1, 1, {GL_RED, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_ALPHA, GL_COMPRESSED_ALPHA, GL_ALPHA, GL_COMPRESSED_ALPHA, 1, {GL_ALPHA, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_INTENSITY, GL_COMPRESSED_INTENSITY, GL_INTENSITY, GL_COMPRESSED_INTENSITY, 1, {GL_INTENSITY, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_LUMINANCE, GL_COMPRESSED_LUMINANCE, GL_LUMINANCE, GL_COMPRESSED_LUMINANCE, 1, {GL_LUMINANCE, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RG, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RG_RGTC2, GL_COMPRESSED_RG, GL_RG, GL_COMPRESSED_RG_RGTC2, 2, {GL_RED, GL_GREEN, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_LUMINANCE_ALPHA, GL_COMPRESSED_LUMINANCE_ALPHA, GL_LUMINANCE_ALPHA, GL_COMPRESSED_LUMINANCE_ALPHA, 2, {GL_LUMINANCE, GL_ALPHA, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGB, GL_COMPRESSED_RGB, GL_RGB, GL_COMPRESSED_RGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, GL_COMPRESSED_RGB, GL_RGB, GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, GL_COMPRESSED_RGB, GL_RGB, GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGB_FXT1_3DFX, GL_COMPRESSED_RGB, GL_RGB, GL_COMPRESSED_RGB_FXT1_3DFX, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGB_S3TC_DXT1_EXT, GL_COMPRESSED_RGB, GL_RGB, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB, GL_COMPRESSED_SRGB, GL_RGB, GL_COMPRESSED_SRGB, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB, GL_RGB, GL_COMPRESSED_SRGB_S3TC_DXT1_EXT, 3, {GL_RED, GL_GREEN, GL_BLUE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA_BPTC_UNORM_ARB, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA_FXT1_3DFX, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA_FXT1_3DFX, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, GL_COMPRESSED_RGBA, GL_RGBA, GL_COMPRESSED_RGBA_S3TC_DXT5_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, {GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, GL_COMPRESSED_SRGB_ALPHA, GL_SRGB_ALPHA, GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT, 4, {GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, true, true}, #endif {GL_NONE, GL_NONE, GL_NONE, GL_NONE, 0, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, {-1, -1, -1, -1}, {GL_NONE, GL_NONE, GL_NONE, GL_NONE}, false, false, false} }; // HdlTextureFormatDescriptor : /** \fn bool HdlTextureFormatDescriptor::isDepthValid(GLenum depth) const \brief Test if a depth is valid for the current format. \param depth The depth to be tested. \return True if the depth can be associated to this format. **/ bool HdlTextureFormatDescriptor::isDepthValid(GLenum depth) const { return (channelsDepth[0]==depth || channelsDepth[0]==GL_NONE) && (channelsDepth[1]==depth || channelsDepth[1]==GL_NONE) && (channelsDepth[2]==depth || channelsDepth[2]==GL_NONE) && (channelsDepth[3]==depth || channelsDepth[3]==GL_NONE); } /** \fn bool HdlTextureFormatDescriptor::hasChannel(GLenum channel) const \brief Returns true if the format has the required channel, false otherwise or raise an exception if the channel is unknown. \param channel The channel name (GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA or GL_LUMINANCE). \return True if the format has the channel. **/ bool HdlTextureFormatDescriptor::hasChannel(GLenum channel) const { return (channels[0]==channel || channels[1]==channel || channels[2]==channel || channels[3]==channel); } /** \fn int HdlTextureFormatDescriptor::getChannelIndex(GLenum channel) const \brief Get the index of a particular channel. \param channel The channel name (GL_RED, GL_GREEN, GL_BLUE, GL_ALPHA or GL_LUMINANCE). \return The channel index or -1 if not found. **/ int HdlTextureFormatDescriptor::getChannelIndex(GLenum channel) const { if(channels[0]==channel) return 0; if(channels[1]==channel) return 1; if(channels[2]==channel) return 2; if(channels[3]==channel) return 3; return -1; } /** \fn int HdlTextureFormatDescriptor::getChannelOffsetInBits(int channelIndex, GLenum depth) const \brief Get the channel offset/position. \param channelIndex The index of the channel \param depth The depth associated with the current format. \return The channel offset in bits or -1 if the channel does not exist. **/ int HdlTextureFormatDescriptor::getChannelOffsetInBits(int channelIndex, GLenum depth) const { if(channelIndex<0 && channelIndex>=numChannels) return -1; else { const int d = getTypeSizeInBits(depth); int r = 0; for(int k=0; k<channelIndex; k++) r += (channelsSizeInBits[k]<0) ? d : channelsSizeInBits[k]; return r; } } /** \fn int HdlTextureFormatDescriptor::getChannelOffset(int channelIndex, GLenum depth) const \brief Get the channel offset/position. \param channelIndex The index of the channel \param depth The depth associated with the current format. \return The channel offset in bytes or -1 if the channel does not exist. **/ int HdlTextureFormatDescriptor::getChannelOffset(int channelIndex, GLenum depth) const { return (getChannelOffsetInBits(channelIndex, depth)+sizeof(char)*8-1)/(sizeof(char)*8); } /** \fn int HdlTextureFormatDescriptor::getChannelSizeInBits(int channelIndex, GLenum depth) const \brief Get the size of a channel. \param channelIndex The index of the channel \param depth The depth associated with the current format. \return The channel size in bits or 0 if the channel does not exist. **/ int HdlTextureFormatDescriptor::getChannelSizeInBits(int channelIndex, GLenum depth) const { if(channelIndex<0 || channelIndex>=numChannels) return 0; else return (channelsSizeInBits[channelIndex]<0) ? getTypeSizeInBits(depth) : channelsSizeInBits[channelIndex]; } /** \fn int HdlTextureFormatDescriptor::getChannelSize(int channelIndex, GLenum depth) const \brief Get the size of a channel. \param channelIndex The index of the channel \param depth The depth associated with the current format. \return The channel size in bytes or 0 if the channel does not exist. **/ int HdlTextureFormatDescriptor::getChannelSize(int channelIndex, GLenum depth) const { return (getChannelSizeInBits(channelIndex, depth)+sizeof(char)*8-1)/(sizeof(char)*8); } /** \fn int HdlTextureFormatDescriptor::getPixelSizeInBits(GLenum depth) const \brief Get the pixel size. \param depth The depth associated with the current format. \return The pixel size in bits. **/ int HdlTextureFormatDescriptor::getPixelSizeInBits(GLenum depth) const { const int d = getTypeSizeInBits(depth); int s = 0; s += (channelsSizeInBits[0]<0) ? d : channelsSizeInBits[0]; s += (channelsSizeInBits[1]<0) ? d : channelsSizeInBits[1]; s += (channelsSizeInBits[2]<0) ? d : channelsSizeInBits[2]; s += (channelsSizeInBits[3]<0) ? d : channelsSizeInBits[3]; return s; } /** \fn int HdlTextureFormatDescriptor::getPixelSize(GLenum depth) const \brief Get the pixel size. \param depth The depth associated with the current format. \return The pixel size in bytes. **/ int HdlTextureFormatDescriptor::getPixelSize(GLenum depth) const { return (getPixelSizeInBits(depth)+sizeof(char)*8-1)/(sizeof(char)*8); } /** \fn int HdlTextureFormatDescriptor::getTypeSizeInBits(GLenum depth) \brief Return the size of the type associated with depth. \param depth The depth, described as its enumerator value (e.g. GL_BYTE for GLbyte). \return Size of the type, in bits. **/ int HdlTextureFormatDescriptor::getTypeSizeInBits(GLenum depth) { switch(depth) { #define TMP_SIZE(X, Type) case X : return sizeof(Type)*8; TMP_SIZE(GL_BYTE, GLbyte ) TMP_SIZE(GL_UNSIGNED_BYTE, GLubyte ) TMP_SIZE(GL_SHORT, GLshort ) TMP_SIZE(GL_UNSIGNED_SHORT, GLushort ) TMP_SIZE(GL_INT, GLint ) TMP_SIZE(GL_UNSIGNED_INT, GLuint ) TMP_SIZE(GL_FLOAT, GLfloat ) #ifdef GLIP_USE_GL TMP_SIZE(GL_DOUBLE, GLdouble ) #endif #undef TMP_SIZE default : throw Exception("HdlTextureFormatDescriptorsList::getTypeSize - cannot recognize color channel depth " + getGLEnumNameSafe(depth), __FILE__, __LINE__, Exception::GLException); } } /** \fn int HdlTextureFormatDescriptor::getTypeSize(GLenum depth) \brief Return the size of the type associated with depth. \param depth The depth, described as its enumerator value (e.g. GL_BYTE for GLbyte). \return Size of the type, in bytes. **/ int HdlTextureFormatDescriptor::getTypeSize(GLenum depth) { switch(depth) { #define TMP_SIZE(X, Type) case X : return sizeof(Type); TMP_SIZE(GL_BYTE, GLbyte ) TMP_SIZE(GL_UNSIGNED_BYTE, GLubyte ) TMP_SIZE(GL_SHORT, GLshort ) TMP_SIZE(GL_UNSIGNED_SHORT, GLushort ) TMP_SIZE(GL_INT, GLint ) TMP_SIZE(GL_UNSIGNED_INT, GLuint ) TMP_SIZE(GL_FLOAT, GLfloat ) #ifdef GLIP_USE_GL TMP_SIZE(GL_DOUBLE, GLdouble ) #endif #undef TMP_SIZE default : throw Exception("HdlTextureFormatDescriptorsList::getTypeSize - cannot recognize color channel depth " + getGLEnumNameSafe(depth), __FILE__, __LINE__, Exception::GLException); } } /** \fn void HdlTextureFormatDescriptor::getShuffle(const HdlTextureFormatDescriptor& dst, const HdlTextureFormatDescriptor& src, char* shuffleIndex, const int length) \brief Construct the shuffling pattern between two format. \param dst The destination format. \param src The source format. \param shuffleIndex Pointer to a buffer which will contain the shuffling pattern. \param length Length of the given buffer (dst.numChannels is sufficient). This function constructs an array containing the index of the channels in the source from the point of view of the destination (or -1 if a channel does not exist in the source). **/ void HdlTextureFormatDescriptor::getShuffle(const HdlTextureFormatDescriptor& dst, const HdlTextureFormatDescriptor& src, char* shuffleIndex, const int length) { char buffer[maxNumChannels]; for(int k=0; k<dst.numChannels; k++) buffer[k] = src.getChannelIndex(dst.channels[k]); // Copy to the maximum length : std::memcpy(shuffleIndex, buffer, std::min(dst.numChannels, length)); } /** \fn int HdlTextureFormatDescriptor::getBitShuffle(const HdlTextureFormatDescriptor& dst, const GLenum& dstDepth, const HdlTextureFormatDescriptor& src, const GLenum& srcDepth, char* shuffleBitIndex, const int length, bool* isBlack) \brief Construct the byte shuffling pattern between two format. \param dst The destination format. \param dstDepth The depth associated with the destination format. \param src The source format. \param srcDepth The depth associated with the source format. \param shuffleBitIndex Pointer to a buffer which will contain the bit shuffling pattern. \param length Length of the given buffer (dst.getPixelSize() is sufficient). \param isBlack If not null, will contain a boolean asserting that there is not correspondence between the source and the destination. \return The length of the pattern actually written. This function constructs an array containing the bit index of the channels in the source from the point of view of the destination (or -1 if a channel does not exist in the source). To be used with HdlTextureFormatDescriptor::applyBitShuffle. It will raise an exception if either or both the source and the destination are floating point formats. **/ int HdlTextureFormatDescriptor::getBitShuffle(const HdlTextureFormatDescriptor& dst, const GLenum& dstDepth, const HdlTextureFormatDescriptor& src, const GLenum& srcDepth, char* shuffleBitIndex, const int length, bool* isBlack) { if(dst.isFloatingPoint || src.isFloatingPoint) throw Exception("HdlTextureFormatDescriptor::getBitShuffle - Cannot construct bits shuffle pattern for floatting point values.", __FILE__, __LINE__, Exception::CoreException); const unsigned int v = 0xFF000000; const bool isLittleEndian = (*reinterpret_cast<const char*>(&v)==0); const int maxLength = maxPixelSize; char buffer[maxLength]; int offset = 0; for(int k=0; k<dst.numChannels; k++) { const int l = src.getChannelIndex(dst.channels[k]); const int dstSize = dst.getChannelSize(k, dstDepth); if(l<0) // src does not have the channel std::memset(buffer+offset, -1, dstSize); else { const int srcSize = src.getChannelSize(l, srcDepth), srcOffset = src.getChannelOffset(l, srcDepth); for(int p=0; p<std::min(srcSize, dstSize); p++) { if(isLittleEndian) buffer[offset + dstSize - p - 1] = srcOffset + srcSize - p - 1; else // big endian buffer[offset + p] = srcOffset + p; } } offset += dstSize; } // If needed, test if there is no correspondance : if(isBlack!=NULL) { (*isBlack) = true; for(int k=0; k<offset; k++) (*isBlack) = (*isBlack) && (buffer[k]<0); } // Copy to the maximum length : offset = std::min(std::min(offset, maxLength), length); std::memcpy(shuffleBitIndex, buffer, offset); #ifdef __GLIPLIB_DEVELOPMENT_VERBOSE__ std::cout << "Shuffle pattern : " << getGLEnumNameSafe(src.mode) << ':' << getGLEnumNameSafe(srcDepth) << " to " << getGLEnumNameSafe(dst.mode) << ':' << getGLEnumNameSafe(dstDepth) << " (offset : " << offset << ')' << std::endl; for(int k=0; k<offset; k++) std::cout << static_cast<int>(shuffleBitIndex[k]) << ", "; std::cout << std::endl; #endif // The length of the pattern : return offset; } /** \fn void HdlTextureFormatDescriptor::applyBitShuffle(char* dst, const char* src, const char* shuffleBitIndex, const int length) \brief Apply the bit shuffling pattern from the source to the destination. \param dst Destination pixel address. \param src Source pixel address. \param shuffleBitIndex Bit shuffle pattern, see HdlTextureFormatDescriptor::getBitShuffle. \param length Length of the shuffling pattern, usually returned by HdlTextureFormatDescriptor::getBitShuffle. **/ void HdlTextureFormatDescriptor::applyBitShuffle(char* dst, const char* src, const char* shuffleBitIndex, const int length) { for(int k=0; k<length; k++) { if(shuffleBitIndex[k]>=0) dst[k] = src[static_cast<int>(shuffleBitIndex[k])]; else dst[k] = 0; } } // HdlTextureFormatDescriptorList : /** \fn int HdlTextureFormatDescriptorsList::getNumDescriptors(void) \brief Returns the number of known GL modes for texture formats (GL_RGB, GL_RGBA, ...). \return Returns the number of known GL modes. **/ int HdlTextureFormatDescriptorsList::getNumDescriptors(void) { static int i = 0; if(i==0) for(i=0; textureFormatDescriptors[i].mode!=GL_NONE; i++); return i; } /** \fn const HdlTextureFormatDescriptor& HdlTextureFormatDescriptorsList::get(int id) \brief Access to a mode descriptor object. Will raise an exception if the index is out of range. \param id Index of the desired descriptor. \return A constant reference onto a HdlTextureFormatDescriptor object. **/ const HdlTextureFormatDescriptor& HdlTextureFormatDescriptorsList::get(int id) { return textureFormatDescriptors[id]; } /** \fn const HdlTextureFormatDescriptor& HdlTextureFormatDescriptorsList::get(const GLenum& mode) \brief Access to a mode descriptor object. Will raise an exception if the mode is unknown. \param mode Searched mode name. \return A constant reference onto a HdlTextureFormatDescriptor object. **/ const HdlTextureFormatDescriptor& HdlTextureFormatDescriptorsList::get(const GLenum& mode) { for(int i=0; textureFormatDescriptors[i].mode!=GL_NONE; i++) if(mode==textureFormatDescriptors[i].mode && mode!=GL_NONE) return textureFormatDescriptors[i]; //else throw Exception("HdlTextureFormatDescriptorsList::get - No corresponding mode for : " + getGLEnumNameSafe(mode) + ".", __FILE__, __LINE__, Exception::GLException); }
.global s_prepare_buffers s_prepare_buffers: push %r8 push %rcx push %rdi push %rsi lea addresses_normal_ht+0xc49, %rsi lea addresses_A_ht+0x9749, %rdi nop and %r8, %r8 mov $89, %rcx rep movsl add %r8, %r8 pop %rsi pop %rdi pop %rcx pop %r8 ret .global s_faulty_load s_faulty_load: push %r11 push %r13 push %r15 push %r8 push %rcx push %rdi push %rsi // REPMOV lea addresses_A+0x1c9c9, %rsi lea addresses_A+0x11549, %rdi nop cmp %r15, %r15 mov $106, %rcx rep movsl nop cmp %rcx, %rcx // Faulty Load lea addresses_WT+0x1e149, %r8 nop nop cmp $3891, %r11 mov (%r8), %di lea oracles, %r13 and $0xff, %rdi shlq $12, %rdi mov (%r13,%rdi,1), %rdi pop %rsi pop %rdi pop %rcx pop %r8 pop %r15 pop %r13 pop %r11 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A', 'congruent': 10, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_WT', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 8, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'00': 2} 00 00 */
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrVkDescriptorPool.h" #include "GrVkGpu.h" #include "SkTemplates.h" GrVkDescriptorPool::GrVkDescriptorPool(const GrVkGpu* gpu, VkDescriptorType type, uint32_t count) : INHERITED() , fType (type) , fCount(count) { VkDescriptorPoolSize poolSize; memset(&poolSize, 0, sizeof(VkDescriptorPoolSize)); poolSize.descriptorCount = count; poolSize.type = type; VkDescriptorPoolCreateInfo createInfo; memset(&createInfo, 0, sizeof(VkDescriptorPoolCreateInfo)); createInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO; createInfo.pNext = nullptr; createInfo.flags = 0; // This is an over/conservative estimate since each set may contain more than count descriptors. createInfo.maxSets = count; createInfo.poolSizeCount = 1; createInfo.pPoolSizes = &poolSize; GR_VK_CALL_ERRCHECK(gpu->vkInterface(), CreateDescriptorPool(gpu->device(), &createInfo, nullptr, &fDescPool)); } bool GrVkDescriptorPool::isCompatible(VkDescriptorType type, uint32_t count) const { return fType == type && count <= fCount; } void GrVkDescriptorPool::reset(const GrVkGpu* gpu) { GR_VK_CALL_ERRCHECK(gpu->vkInterface(), ResetDescriptorPool(gpu->device(), fDescPool, 0)); } void GrVkDescriptorPool::freeGPUData(GrVkGpu* gpu) const { // Destroying the VkDescriptorPool will automatically free and delete any VkDescriptorSets // allocated from the pool. GR_VK_CALL(gpu->vkInterface(), DestroyDescriptorPool(gpu->device(), fDescPool, nullptr)); }
/* * Copyright 2002-2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * CC/LICENSE * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "node_bridgeex.h" #include "fs_opr.h" #include "fs_mgr.h" node_bridgeex_t::node_bridgeex_t(const uint32_t id, const string& name, const string& type, const string& desc, const key_map_t& keymap) : NodeResource(id, name, type, desc, keymap) { } NodeBase* node_bridgeex_t::run(base_script_t* param) { if (NULL == param) { IVR_WARN("base_script_t pointer should not be null"); return NULL; } IVR_TRACE("%s", enter(param->name_var_map).c_str()); const char* exit = EXIT_FAIL; string caller; string called; string calltype; string bgmfile; bool usebgm = true; std::string callid; fw_id_t fs_no = param->fid; void* ptmp = param->name_var_map[SYS_VAR[sys_var_t::CALLID]].pvalue; if (ptmp) { callid = *(std::string*)ptmp; } if (strcasecmp(_bgtype.c_str(), PARAMITEM_RING) != 0 && strcasecmp(_bgtype.c_str(), PARAMITEM_BGM) != 0) { IVR_WARN("bgtype error, USE ring"); usebgm = false; } else if (strcasecmp(_bgtype.c_str(), PARAMITEM_RING) == 0) { usebgm = false; } else if (strcasecmp(_bgtype.c_str(), PARAMITEM_BGM) == 0 && _bgmfile.length() == 0) { IVR_WARN("BGM file is null, use ring"); usebgm = false; } parse_expression(_bgmfile, param->name_var_map, bgmfile); if (true == parse_expression(_caller, param->name_var_map, caller) && true == parse_expression(_called, param->name_var_map, called) && true == parse_expression(_calltype, param->name_var_map, calltype) && true == parse_expression(_callid, param->name_var_map, callid)) { IVR_TRACE("caller=%s,called=%s,callid=%s,bgtype=%s(usebgm:%d),bgmfile=%s", caller.c_str(), called.c_str(), callid.c_str(), _bgtype.c_str(), usebgm, bgmfile.c_str()); fs_opr_t* opr = NULL; if (fs_mgr_t::instance()->fetch_opr(fs_no, &opr) == IVR_SUCCESS) { if (NULL != opr) { if (IVR_SUCCESS == opr->bridgeex(callid.c_str(), caller.c_str(), called.c_str(), calltype != "0", usebgm, bgmfile.c_str())) { exit = EXIT_SUCC; } else { IVR_WARN("bridgeex failed(caller: %s, called: %s)", _caller.c_str(), _called.c_str()); } fs_mgr_t::instance()->free_opr(&opr); } else { IVR_WARN("fs_opr_t pointer should not be null"); } } else { IVR_WARN("fetch opr failed. freeswitch no is %d", fs_no); } } else { IVR_WARN("caller or called parse failed(%s,%s)", _caller.c_str(), _called.c_str()); } NodeBase* exit_node_ptr = NULL; std::map<std::string, NodeBase*>::iterator citr; citr = _exit_node_map.find(exit); if (citr != _exit_node_map.end()) { exit_node_ptr = citr->second; IVR_TRACE("%s exit from %s(bridgeex to %s)", leave(param->name_var_map).c_str(), exit, called.c_str()); } else { IVR_WARN("Can not find exit %s in _exit_node_map", exit); } return exit_node_ptr; } bool node_bridgeex_t::load_other() { valid_str(_key_map, PARAM_BGTYPE, _bgtype); valid_str(_key_map, PARAM_BGMFILE, _bgmfile); return NodeResource::load_other() && valid_str(_key_map, PARAM_CALLER, _caller) && valid_str(_key_map, PARAM_CALLED, _called) && valid_str(_key_map, PARAM_CALLTYPE, _calltype); } std::string node_bridgeex_t::enter(const map<string, variable_t>& vars) const { ostringstream ostm; ostm << NodeBase::enter(vars); ostm << "caller:" << _caller << ",called:" << _called; return ostm.str(); } const char* node_bridgeex_t::PARAM_CALLER = "callernumber"; const char* node_bridgeex_t::PARAM_CALLED = "callednumber"; const char* node_bridgeex_t::PARAM_CALLTYPE = "calltype"; const char* node_bridgeex_t::PARAM_BGTYPE = "bgtype"; const char* node_bridgeex_t::PARAM_BGMFILE = "bgmfile"; const char* node_bridgeex_t::PARAMITEM_BGM = "bgm"; const char* node_bridgeex_t::PARAMITEM_RING = "ring"; /* vim: set expandtab ts=4 sw=4 sts=4 tw=100: */
; Copyright Terence J. Boldt (c)2020-2022 ; Use of this source code is governed by an MIT ; license that can be found in the LICENSE file. ; This file contains the source for the firmware ; that was formerly used to act as a pseudo-shell ;ProDOS Zero Page Command = $42 ;ProDOS Command Unit = $43 ;ProDOS unit (SDDD0000) BufferLo = $44 BufferHi = $45 BlockLo = $46 BlockHi = $47 ; ProDOS Error Codes IOError = $27 NoDevice = $28 WriteProtect = $2B InputByte = $c08e+SLOT*$10 OutputByte = $c08d+SLOT*$10 InputFlags = $c08b+SLOT*$10 OutputFlags = $c087+SLOT*$10 ReadBlockCommand = $01 WriteBlockCommand = $02 GetTimeCommand = $03 ChangeDriveCommand = $04 ExecCommand = $05 LoadFileCommand = $06 SaveFileCommand = $07 MenuCommand = $08 InputString = $fd67 PrintChar = $fded Keyboard = $c000 ClearKeyboard = $c010 Wait = $fca8 .org SLOT*$100 + $C000 ;ID bytes for booting and drive detection cpx #$20 ;ID bytes for ProDOS and the cpx #$00 ; Apple Autostart ROM cpx #$03 ; ldx #SLOT*$10 stx $2b stx Unit ;force EPROM to second page on boot lda #$3f ;set all flags high and page 3 of EPROM for menu PageJump: sta OutputFlags jmp Start ;this jump is only called if coming in from PageJump with A=$2f ;entry points for ProDOS DriverEntry: lda #$0f ;set all flags high and page 0 of EPROM sta OutputFlags Start: jsr $c300 ;enable 80 columns lda #$05 ;execute command jsr SendByte ldy #$00 sendHelp: lda HelpCommand,y beq endSendHelp jsr SendByte iny bne sendHelp endSendHelp: lda #$00 jsr SendByte jsr DumpOutput lda $33 pha lda #$a4 sta $33 GetCommand: jsr InputString lda $0200 cmp #$8d ;skip when return found beq GetCommand jsr SendCommand clc bcc GetCommand SendCommand: bit ClearKeyboard lda #$05 ;send command 5 = exec jsr SendByte ldy #$00 getInput: lda $0200,y cmp #$8d beq sendNullTerminator and #$7f jsr SendByte iny bne getInput sendNullTerminator: lda #$00 jsr SendByte DumpOutput: jsr GetByte bcs skipOutput cmp #$00 beq endOutput jsr PrintChar skipOutput: bit Keyboard ;check for keypress bpl DumpOutput ;keep dumping output if no keypress lda Keyboard ;send keypress to RPi jsr PrintChar and #$7f jsr SendByte bit ClearKeyboard clc bcc DumpOutput endOutput: rts HelpCommand: .byte "a2help",$00 SendByte: pha waitWrite: lda InputFlags rol rol bcs waitWrite pla sta OutputByte lda #$1e ; set bit 0 low to indicate write started sta OutputFlags finishWrite: lda InputFlags rol rol bcc finishWrite lda #$1f sta OutputFlags rts GetByte: lda #$1d ;set read flag low sta OutputFlags waitRead: lda InputFlags rol bcc readByte bit Keyboard ;keypress will abort waiting to read bpl waitRead lda #$1f ;set all flags high and exit sta OutputFlags sec ;failure rts readByte: lda InputByte pha lda #$1f ;set all flags high sta OutputFlags finishRead: lda InputFlags rol bcc finishRead pla clc ;success end: rts .repeat 251-<end .byte 0 .endrepeat .byte 0,0 ;0000 blocks = check status .byte 7 ;bit set(0=status 1=read 2=write) unset(3=format, 4/5=number of volumes, 6=interruptable, 7=removable) .byte DriverEntry&$00FF ;low byte of entry
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/c/c_api_experimental.h" #include "tensorflow/c/c_api_internal.h" #include "tensorflow/c/c_test_util.h" #include "tensorflow/c/eager/c_api.h" #include "tensorflow/c/eager/c_api_test_util.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/protobuf/tensorflow_server.pb.h" namespace tensorflow { namespace { TEST(CAPI_EXPERIMENTAL, GetServerDefTest) { const string expected_text_proto(R"(cluster { job { name: "worker" tasks { key: 0 value: "tpuserver:0" } tasks { key: 1 value: "localhost:1" } } } job_name: "worker" task_index: 1 protocol: "grpc" )"); TF_Status* status = TF_NewStatus(); TF_Buffer* result = TFE_GetServerDef(expected_text_proto.c_str(), status); EXPECT_EQ(TF_GetCode(status), TF_OK); ServerDef actual; ASSERT_TRUE(actual.ParseFromArray(result->data, result->length)); string actual_text_proto; tensorflow::protobuf::TextFormat::PrintToString(actual, &actual_text_proto); EXPECT_EQ(expected_text_proto, actual_text_proto); const string malformed_text_proto(R"(cluster { job { name: "worker")"); TF_Buffer* null_result = TFE_GetServerDef(malformed_text_proto.c_str(), status); EXPECT_NE(TF_GetCode(status), TF_OK); EXPECT_TRUE(absl::StrContains(TF_Message(status), "Invalid text proto for ServerDef")); EXPECT_EQ(null_result, nullptr); // Cleanup TF_DeleteBuffer(result); TF_DeleteStatus(status); } TEST(CAPI_EXPERIMENTAL, IsStateful) { std::unique_ptr<TF_Status, decltype(&TF_DeleteStatus)> status( TF_NewStatus(), TF_DeleteStatus); int assign = TF_OpIsStateful("AssignAddVariableOp", status.get()); ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get()); EXPECT_EQ(assign, 1); int id = TF_OpIsStateful("Identity", status.get()); ASSERT_EQ(TF_OK, TF_GetCode(status.get())) << TF_Message(status.get()); EXPECT_EQ(id, 0); } TEST(CAPI_EXPERIMENTAL, TFE_ExecuteOpInNewThreadTest_Simple) { TF_Status* status = TF_NewStatus(); TFE_ContextOptions* opts = TFE_NewContextOptions(); TFE_Context* ctx = TFE_NewContext(opts, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_DeleteContextOptions(opts); TFE_TensorHandle* m = TestMatrixTensorHandle(); TFE_Op* matmul_op = MatMulOp(ctx, m, m); TFE_TensorHandle* retvals[1] = {nullptr}; int num_retvals = 1; auto* r = TFE_ExecuteOpInNewThread(matmul_op, &retvals[0], &num_retvals, status); TFE_ExecuteOpNotificationWaitAndDelete(r, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TF_Tensor* t = TFE_TensorHandleResolve(retvals[0], status); ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); float product[4] = {0}; EXPECT_EQ(sizeof(product), TF_TensorByteSize(t)); memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t)); TF_DeleteTensor(t); EXPECT_EQ(7, product[0]); EXPECT_EQ(10, product[1]); EXPECT_EQ(15, product[2]); EXPECT_EQ(22, product[3]); TFE_DeleteOp(matmul_op); TFE_DeleteTensorHandle(m); TFE_DeleteTensorHandle(retvals[0]); TFE_DeleteContext(ctx); TF_DeleteStatus(status); } // Perform a send/recv test. Recv blocks, so they need to be executed // asynchronously. TEST(CAPI_EXPERIMENTAL, TFE_ExecuteOpInNewThreadTest_Blocking) { TF_Status* status = TF_NewStatus(); TFE_ContextOptions* opts = TFE_NewContextOptions(); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_Context* ctx = TFE_NewContext(opts, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_DeleteContextOptions(opts); // Returns a 2x2 float32 Tensor on the CPU, with data 1., 2., 3., 4. TFE_TensorHandle* m = TestMatrixTensorHandle(); // Build a send op. TFE_Op* send_op = TFE_NewOp(ctx, "_Send", status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_OpAddInput(send_op, m, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); string tensor_name = "Tensor"; TFE_OpSetAttrType(send_op, "T", TF_FLOAT); TFE_OpSetAttrString(send_op, "tensor_name", tensor_name.c_str(), tensor_name.size()); string send_device = "/job:localhost/replica:0/task:0/device:CPU:0"; TFE_OpSetAttrString(send_op, "send_device", send_device.c_str(), send_device.size()); TFE_OpSetAttrInt(send_op, "send_device_incarnation", 1234); string recv_device = "/job:localhost/replica:0/task:0/device:CPU:0"; TFE_OpSetAttrString(send_op, "recv_device", recv_device.c_str(), recv_device.size()); TFE_OpSetAttrBool(send_op, "client_terminated", true); // Build a recv op. TFE_Op* recv_op = TFE_NewOp(ctx, "_Recv", status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_OpSetAttrType(recv_op, "tensor_type", TF_FLOAT); TFE_OpSetAttrString(recv_op, "tensor_name", tensor_name.c_str(), tensor_name.size()); TFE_OpSetAttrString(recv_op, "send_device", send_device.c_str(), send_device.size()); TFE_OpSetAttrInt(recv_op, "send_device_incarnation", 1234); TFE_OpSetAttrString(recv_op, "recv_device", recv_device.c_str(), recv_device.size()); TFE_OpSetAttrBool(recv_op, "client_terminated", true); TFE_TensorHandle* send_retvals; int send_num_retvals = 0; auto* send_result = TFE_ExecuteOpInNewThread(send_op, &send_retvals, &send_num_retvals, status); TFE_TensorHandle* recv_retvals[1] = {nullptr}; int recv_num_retvals = 1; auto* recv_result = TFE_ExecuteOpInNewThread(recv_op, &recv_retvals[0], &recv_num_retvals, status); TFE_ExecuteOpNotificationWaitAndDelete(send_result, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TFE_ExecuteOpNotificationWaitAndDelete(recv_result, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); TF_Tensor* t = TFE_TensorHandleResolve(recv_retvals[0], status); ASSERT_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); float product[4] = {0}; EXPECT_EQ(sizeof(product), TF_TensorByteSize(t)); memcpy(&product[0], TF_TensorData(t), TF_TensorByteSize(t)); TF_DeleteTensor(t); EXPECT_EQ(1, product[0]); EXPECT_EQ(2, product[1]); EXPECT_EQ(3, product[2]); EXPECT_EQ(4, product[3]); TFE_DeleteOp(send_op); TFE_DeleteOp(recv_op); TFE_DeleteTensorHandle(m); TFE_DeleteTensorHandle(recv_retvals[0]); TFE_DeleteContext(ctx); TF_DeleteStatus(status); } TEST(CAPI_EXPERIMENTAL, SymbolicTensor) { TF_Status* status = TF_NewStatus(); auto node = TF_Output{nullptr, 1}; auto* sym_handle = TFE_NewTensorHandleFromTFOutput(node, TF_FLOAT); TFE_TensorHandlePrintDebugString(sym_handle); CHECK_EQ(TFE_TensorHandleDataType(sym_handle), TF_FLOAT); ASSERT_FALSE(TFE_TensorHandleIsConcrete(sym_handle)); auto same_node = TFE_GetTFOutputFromTensorHandle(sym_handle, status); CHECK_EQ(TF_OK, TF_GetCode(status)) << TF_Message(status); ASSERT_EQ(same_node.oper, node.oper); ASSERT_EQ(same_node.index, node.index); TFE_DeleteTensorHandle(sym_handle); TFE_TensorHandle* m = TestMatrixTensorHandle(); ASSERT_TRUE(TFE_TensorHandleIsConcrete(m)); (void)TFE_GetTFOutputFromTensorHandle(m, status); CHECK_EQ(TF_INTERNAL, TF_GetCode(status)) << TF_Message(status); TFE_DeleteTensorHandle(m); TF_DeleteStatus(status); } class AddEagerOpToGraphTest : public ::testing::Test { protected: AddEagerOpToGraphTest() : status_(TF_NewStatus()), eager_ctx_(nullptr), graph_(TF_NewGraph()), trace_ctx_(TFE_NewTraceContext(graph_)) { TFE_ContextOptions* opts = TFE_NewContextOptions(); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); eager_ctx_ = TFE_NewContext(opts, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); TFE_DeleteContextOptions(opts); } ~AddEagerOpToGraphTest() override { TFE_DeleteTraceContext(trace_ctx_); TF_DeleteGraph(graph_); TFE_DeleteContext(eager_ctx_); TF_DeleteStatus(status_); } template <typename Callable> void AddEagerOpToGraphAndCheck(TFE_Op* op, Callable checker) { TFE_TensorHandle* retvals[5]; int num_retvals = 5; // Symbolically execute this op, which adds a graph node to `trace_ctx_`. TF_Operation* graph_op = TFE_AddEagerOpToGraph(op, trace_ctx_, retvals, &num_retvals, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_NOTNULL(graph_op); // Check the expectations. checker(graph_op); for (int i = 0; i < num_retvals; ++i) { TFE_DeleteTensorHandle(retvals[i]); } } TF_Status* status_; TFE_Context* eager_ctx_; TF_Graph* graph_; TFE_TraceContext* trace_ctx_; }; TEST_F(AddEagerOpToGraphTest, DebugPrintAndSymbolicExecution) { TFE_TensorHandle* m = TestMatrixTensorHandle(); TFE_Op* op = MatMulOp(eager_ctx_, m, m); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); TFE_OpPrintDebugString(op); TFE_TensorHandle* retvals[5]; int num_retvals = 5; // Symbolically execute this op, which adds a graph node to `trace_ctx`. TFE_AddEagerOpToGraph(op, trace_ctx_, retvals, &num_retvals, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); int num_inputs = TFE_FinalizeInputTensorsFromTraceContext(trace_ctx_); CHECK_EQ(num_inputs, 1); auto input_sym_tensor = TFE_GetInputGraphNodeFromTraceContext(trace_ctx_, /*idx*/ 0); LOG(INFO) << tensorflow::getTF_OutputDebugString(input_sym_tensor); auto handle = TFE_ConsumeInputConcreteTensorFromTraceContext(trace_ctx_, /*idx*/ 0); TFE_TensorHandlePrintDebugString(handle); TFE_DeleteTensorHandle(handle); CHECK_EQ(num_retvals, 1); CHECK_EQ(TFE_TensorHandleDataType(retvals[0]), TF_FLOAT); TFE_DeleteTensorHandle(retvals[0]); TFE_DeleteTensorHandle(m); TFE_DeleteOp(op); } TEST_F(AddEagerOpToGraphTest, ValueAttributesArePreserved) { // Create MinOp TFE_TensorHandle* axis = TestAxisTensorHandle(); TFE_Op* op = MinOp(eager_ctx_, axis, axis); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); // Check the attributes set by the call to MinOp above. AddEagerOpToGraphAndCheck(op, [this, &axis](TF_Operation* graph_op) { unsigned char value; TF_OperationGetAttrBool(graph_op, "keep_dims", &value, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_EQ(value, 1); TF_DataType dtype; TF_OperationGetAttrType(graph_op, "Tidx", &dtype, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_EQ(dtype, TF_INT32); TF_OperationGetAttrType(graph_op, "T", &dtype, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_EQ(dtype, TFE_TensorHandleDataType(axis)); }); TFE_DeleteTensorHandle(axis); TFE_DeleteOp(op); } TEST_F(AddEagerOpToGraphTest, ListAttributesArePreserved) { // Create a "Squeeze" operator with list attributes. TFE_TensorHandle* axis = TestAxisTensorHandle(); TFE_Op* squeeze = TFE_NewOp(eager_ctx_, "Squeeze", status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); TFE_OpAddInput(squeeze, axis, status_); TFE_OpSetAttrType(squeeze, "T", TF_INT32); std::vector<int64_t> boundaries = {1, 2, 3, 4}; TFE_OpSetAttrIntList(squeeze, "squeeze_dims", boundaries.data(), boundaries.size()); // Check attributes are preserved. AddEagerOpToGraphAndCheck( squeeze, [this, &boundaries](TF_Operation* squeeze_graph_op) { TF_DataType dtype; TF_OperationGetAttrType(squeeze_graph_op, "T", &dtype, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_EQ(dtype, TF_INT32); std::unique_ptr<int64_t[]> list(new int64_t[boundaries.size()]); TF_OperationGetAttrIntList(squeeze_graph_op, "squeeze_dims", list.get(), boundaries.size(), status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); EXPECT_TRUE(std::equal(list.get(), list.get() + boundaries.size(), boundaries.begin())); }); TFE_DeleteTensorHandle(axis); TFE_DeleteOp(squeeze); } TEST_F(AddEagerOpToGraphTest, ListInputsAreAddedCorrectly) { TFE_TensorHandle* scalar = TestScalarTensorHandle(static_cast<float>(1)); TFE_Op* identityn = TFE_NewOp(eager_ctx_, "IdentityN", status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); constexpr size_t kNumInputs = 3; for (size_t i = 0; i < kNumInputs; ++i) { TFE_OpAddInput(identityn, scalar, status_); } TF_DataType types[kNumInputs] = {TF_FLOAT, TF_FLOAT, TF_FLOAT}; TFE_OpSetAttrTypeList(identityn, "T", types, kNumInputs); AddEagerOpToGraphAndCheck( identityn, [this, kNumInputs](TF_Operation* graph_op) { EXPECT_EQ(TF_OperationNumInputs(graph_op), kNumInputs); EXPECT_EQ(TF_OperationInputListLength(graph_op, "input", status_), kNumInputs); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); EXPECT_EQ(TF_OperationOutputListLength(graph_op, "output", status_), kNumInputs); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); }); TFE_DeleteTensorHandle(scalar); TFE_DeleteOp(identityn); } TEST_F(AddEagerOpToGraphTest, NumberAttributesAreHandledCorrectly) { TFE_TensorHandle* matrix = TestMatrixTensorHandle(); TFE_TensorHandle* axis = TestAxisTensorHandle(); TFE_Op* concatv2 = TFE_NewOp(eager_ctx_, "ConcatV2", status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); TFE_OpSetAttrType(concatv2, "T", TF_FLOAT); TFE_OpSetAttrInt(concatv2, "N", 2); TFE_OpSetAttrType(concatv2, "Tidx", TF_INT32); constexpr size_t kNumInputs = 2; for (size_t i = 0; i < kNumInputs; ++i) { TFE_OpAddInput(concatv2, matrix, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); } TFE_OpAddInput(concatv2, axis, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); AddEagerOpToGraphAndCheck( concatv2, [this, kNumInputs](TF_Operation* graph_op) { EXPECT_EQ(TF_OperationNumInputs(graph_op), kNumInputs + 1); int64_t attrN; TF_OperationGetAttrInt(graph_op, "N", &attrN, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); EXPECT_EQ(attrN, kNumInputs); EXPECT_EQ(TF_OperationInputListLength(graph_op, "values", status_), kNumInputs); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); }); TFE_DeleteTensorHandle(axis); TFE_DeleteTensorHandle(matrix); TFE_DeleteOp(concatv2); } TEST_F(AddEagerOpToGraphTest, GeneratesInternalErrorsForInvalidNumberAttributes) { TFE_TensorHandle* matrix = TestMatrixTensorHandle(); TFE_TensorHandle* axis = TestAxisTensorHandle(); int num_retvals = 5; TFE_TensorHandle* retvals[5]; TFE_Op* concatv2 = TFE_NewOp(eager_ctx_, "ConcatV2", status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); TFE_OpSetAttrType(concatv2, "T", TF_FLOAT); TFE_OpSetAttrInt(concatv2, "N", -1); TFE_OpSetAttrType(concatv2, "Tidx", TF_INT32); TF_Operation* graph_op = TFE_AddEagerOpToGraph(concatv2, trace_ctx_, retvals, &num_retvals, status_); EXPECT_EQ(graph_op, nullptr); EXPECT_EQ(status_->status.error_message(), "Number attribute for length should be >=0!"); TFE_DeleteOp(concatv2); TFE_DeleteTensorHandle(axis); TFE_DeleteTensorHandle(matrix); } class ShapeInferenceTest : public ::testing::Test { protected: ShapeInferenceTest() : status_(TF_NewStatus()), tfe_context_options_(TFE_NewContextOptions()) { tfe_context_ = TFE_NewContext(tfe_context_options_, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); matmul_op_ = TFE_NewOp(tfe_context_, "MatMul", status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); } ~ShapeInferenceTest() override { TFE_DeleteOp(matmul_op_); TFE_DeleteContextOptions(tfe_context_options_); TFE_DeleteContext(tfe_context_); TF_DeleteStatus(status_); } void infer_matmul_shapes(TF_ShapeAndTypeList* input_shapes, int64_t expected_rank, int64_t expected_first_dim, int64_t expected_second_dim) { TF_ShapeAndTypeList* output_shapes; TFE_InferShapes(matmul_op_, input_shapes, /*input_tensors*/ nullptr, /*input_tensors_as_shapes*/ nullptr, /*input_resource_shapes_and_types*/ nullptr, &output_shapes, /*output_resource_shapes_and_types*/ nullptr, status_); CHECK_EQ(TF_OK, TF_GetCode(status_)) << TF_Message(status_); CHECK_EQ(output_shapes->num_items, 1); EXPECT_EQ(output_shapes->items[0].num_dims, expected_rank); if (expected_rank == 2) { EXPECT_EQ(output_shapes->items[0].dims[0], expected_first_dim); EXPECT_EQ(output_shapes->items[0].dims[1], expected_second_dim); } TF_DeleteShapeAndTypeList(input_shapes); TF_DeleteShapeAndTypeList(output_shapes); } TF_Status* status_; TFE_ContextOptions* tfe_context_options_; TFE_Context* tfe_context_; TFE_Op* matmul_op_; }; TEST_F(ShapeInferenceTest, InfersShapes) { // Infer shape when everything is known. int64_t _3by2[] = {3, 2}; int64_t _2by4[] = {2, 4}; TF_ShapeAndTypeList* input_shapes = TF_NewShapeAndTypeList(/*num_shapes*/ 2); TF_ShapeAndTypeListSetShape(input_shapes, 0, _3by2, 2); TF_ShapeAndTypeListSetShape(input_shapes, 1, _2by4, 2); infer_matmul_shapes(input_shapes, /*expected_rank*/ 2, /*expected_first_dim*/ 3, /*expected_second_dim*/ 4); // Infer shape when second operand has unknown shape. TF_ShapeAndTypeList* input_shapes_unknown_second = TF_NewShapeAndTypeList(/*num_shapes*/ 2); TF_ShapeAndTypeListSetShape(input_shapes_unknown_second, 0, _3by2, 2); TF_ShapeAndTypeListSetUnknownShape(input_shapes_unknown_second, 1); infer_matmul_shapes( input_shapes_unknown_second, /*expected_rank*/ 2, /*expected_first_dim*/ 3, /*expected_second_dim*/ shape_inference::InferenceContext::kUnknownDim); // Infer shape when some dimensions are unknown. int64_t _unknownby2[] = {-1, 2}; TF_ShapeAndTypeList* input_shapes_unknown_dims = TF_NewShapeAndTypeList(/*num_shapes*/ 2); TF_ShapeAndTypeListSetShape(input_shapes_unknown_dims, 0, _unknownby2, 2); TF_ShapeAndTypeListSetShape(input_shapes_unknown_dims, 1, _2by4, 2); infer_matmul_shapes( input_shapes_unknown_dims, /*expected_rank*/ 2, /*expected_first_dim*/ shape_inference::InferenceContext::kUnknownDim, /*expected_second_dim*/ 4); // Infer shape when everything is unknown. TF_ShapeAndTypeList* unknown_shapes = TF_NewShapeAndTypeList(/*num_shapes*/ 2); TF_ShapeAndTypeListSetUnknownShape(unknown_shapes, 0); TF_ShapeAndTypeListSetUnknownShape(unknown_shapes, 1); infer_matmul_shapes( unknown_shapes, /*expected_rank*/ 2, /*expected_first_dim*/ shape_inference::InferenceContext::kUnknownDim, /*expected_second_dim*/ shape_inference::InferenceContext::kUnknownDim); // TODO(bgogul): Add some death tests where status is not OK. } } // namespace } // namespace tensorflow
SFX_Cry0C_1_Ch4: dutycycle 204 squarenote 8, 15, 5, 1536 squarenote 2, 13, 2, 1592 squarenote 2, 12, 2, 1584 squarenote 2, 12, 2, 1576 squarenote 2, 11, 2, 1568 squarenote 2, 11, 2, 1552 squarenote 2, 10, 2, 1560 squarenote 2, 11, 2, 1552 squarenote 8, 12, 1, 1568 endchannel SFX_Cry0C_1_Ch5: dutycycle 68 squarenote 12, 12, 3, 1472 squarenote 3, 11, 1, 1529 squarenote 2, 10, 1, 1521 squarenote 2, 10, 1, 1513 squarenote 2, 9, 1, 1505 squarenote 2, 9, 1, 1497 squarenote 2, 8, 1, 1489 squarenote 2, 9, 1, 1497 squarenote 8, 9, 1, 1505 SFX_Cry0C_1_Ch7: endchannel
; file descriptors %define STDIN 0 %define STDOUT 1 ; syscalls %define SYS_READ 0 %define SYS_WRITE 1 %define SYS_MMAP 9 %define SYS_MUNMAP 11 %define SYS_EXIT 60 ; dedicating a register to the buffer %define buffer r15 %define max_buffer_len 5000h %define ANSWERED 88 %define UNANSWERED 111 %define LETTER_START 97 %define LETTER_END 122 section .data num_buffer: db 0, 0, 0, 0, 0, 0, 0, 0 num_buffer_len: equ $ - num_buffer ans_buffer: db 'oooooooooooooooooooooooooo', 0Ah ans_buffer_len: equ $ - ans_buffer error_msg: db 'ERROR', 0Ah error_len: equ $ - error_msg section .text global _start _start: ; read the input into a mmap'd buffer call alloc_buffer call read_file ; read_file stored the length in rax call run ; Write the number call print_number mov rdx, rax mov eax, SYS_WRITE mov edi, STDOUT lea rsi, [rel num_buffer] syscall call free_buffer mov eax, SYS_EXIT xor rdi, rdi syscall alloc_buffer: ; Allocate some space with mmap mov eax, SYS_MMAP xor rdi, rdi ; addr is null mov rsi, max_buffer_len mov rdx, 3 ; PROT_READ | PROT_WRITE mov r10, 22h ; MAP_ANONYMOUS | MAP_PRIVATE mov r8, -1 ; set fd to -1 for portability syscall test rax, rax ; if the result is negative, error js error mov buffer, rax ret free_buffer: mov eax, SYS_MUNMAP mov rdi, buffer mov rsi, max_buffer_len syscall test rax, rax jnz error ret read_file: mov r14, buffer ; r14 is current pointer _do_read: mov eax, SYS_READ mov rdi, STDIN mov rsi, r14 mov rdx, max_buffer_len syscall test rax, rax js error ; negative result means badness jz _done_read ; 0 result means doneness ; anything else means try again add r14, rax jmp _do_read _done_read: sub r14, buffer mov rax, r14 ret print_number: ; number is in eax ; get a pointer to the end of our buffer lea rsi, [rel num_buffer] ; track the offset of the result string in r13 mov r13, 7 _print_digit: mov edx, 0 mov ecx, 10 div ecx ; stores ecx / 10 in eax, ecx % 10 in edx add edx, 48 ; convert remainder to ascii mov [rsi+r13], dl ; store lower byte in rsi sub r13, 1 test eax, eax jnz _print_digit ; return the length of the string add r13, 1 mov rax, 8 sub rax, r13 ; we have a string at the end of the buffer ; copy it to the start mov r12, rax _copy_digit: mov dl, [rsi+r13] mov [rsi], dl add rsi, 1 sub r12, 1 jnz _copy_digit ret run: ; eax is the size of the input xor r8, r8 ; answer goes in r8 mov rsi, buffer lea rdi, [rel ans_buffer] mov r10, rax xor rax, rax _read_char: ; read input, decrement counter mov al, [rsi] and rax, 0x7f add rsi, 1 sub r10, 1 cmp al, 0Ah je _newline _handle_letter: cmp al, LETTER_START jb error cmp al, LETTER_END ja error ; it's a valid char, convert it to an offset sub al, LETTER_START mov byte [rdi + rax], ANSWERED jmp _read_char _newline: ; if there is no more input, we are done test r10, r10 jz _group_done ; read input, decrement counter mov al, [rsi] and rax, 0x7f add rsi, 1 sub r10, 1 cmp al, 0Ah jne _handle_letter _group_done: ; debug: print the line %if 0 mov r9, rsi mov eax, SYS_WRITE mov edi, STDOUT lea rsi, [rel ans_buffer] mov rdx, ans_buffer_len syscall mov rdi, rsi mov rsi, r9 %endif xor rcx, rcx _group_loop: mov al, [rdi + rcx] and rax, 0x7f cmp al, ANSWERED jne _group_loop_next add r8, 1 _group_loop_next: mov byte [rdi + rcx], UNANSWERED add rcx, 1 cmp rcx, 26 jne _group_loop ; if we have input left, keep reading test r10, r10 jnz _read_char ; otherwise, we're done! mov rax, r8 ret error: ; assume error code is in RAX mov r14, rax ;print error message mov eax, SYS_WRITE mov edi, STDOUT lea rsi, [rel error_msg] mov rdx, error_len syscall mov rdi, r14 ; if it is negative, negate it test rdi, rdi jns _exit neg rdi _exit: mov eax, SYS_EXIT syscall
; Kill current job section utility xdef ut_kill,gu_die include win1_keys_qdos_sms ;+++ ; Kill current job ;--- ut_kill gu_die moveq #0,d3 moveq #-1,d1 moveq #sms.frjb,d0 trap #do.sms2 end
; A221882: Number of order-preserving or order-reversing full contraction mappings of an n-chain. ; 1,4,13,36,91,218,505,1144,2551,5622,12277,26612,57331,122866,262129,557040,1179631,2490350,5242861,11010028,23068651,48234474,100663273,209715176,436207591,905969638,1879048165,3892314084,8053063651,16642998242,34359738337 mov $1,$0 add $0,2 mov $2,2 pow $2,$1 sub $2,1 mul $0,$2 add $0,1
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2021, Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; %define GCM128_MODE 1 %include "avx512/gcm_sgl_api_vaes_avx512.inc"
add $t0, $s1, $s2 # i = N*N + 3*N 1_Unoptimized: lw $t0, 4($gp) # fetch N mult $t0, $t0, $t0 # N*N lw $t1, 4($gp) # fetch N ori $t2, $zero, 3 # 3 mult $t1, $t1, $t2 # 3*N add $t2, $t0, $t1 # N*N + 3*N sw $t2, 0($gp) # i = ... 1_Optimized: lw $t0, 4($gp) # fetch N add $t1, $t0, $zero # copy N to $t1 addi $t1, $t1, 3 # N+3 mult $t1, $t1, $t0 # N*(N+3) sw $t1, 0($gp) # i = ... # A[i] = A[i/2] + 1; # A[i+1] = -1; 2_Unoptimized: # A[i] = A[i/2] + 1; lw $t0, 0($gp) # fetch i srl $t0, $t0, 1 # i/2 addi $t1, $gp, 28 # &A[0] sll $t0, $t0, 2 # turn i/2 into a byte offset (*4) add $t1, $t1, $t0 # &A[i/2] lw $t1, 0($t1) # fetch A[i/2] addi $t1, $t1, 1 # A[i/2] + 1 lw $t0, 0($gp) # fetch i sll $t0, $t0, 2 # turn i into a byte offset addi $t2, $gp, 28 # &A[0] add $t2, $t2, $t0 # &A[i] sw $t1, 0($t2) # A[i] = ... # A[i+1] = -1; lw $t0, 0($gp) # fetch i addi $t0, $t0, 1 # i+1 sll $t0, $t0, 2 # turn i+1 into a byte offset addi $t1, $gp, 28 # &A[0] add $t1, $t1, $t0 # &A[i+1] addi $t2, $zero, -1 # -1 sw $t2, 0($t1) # A[i+1] = -1 2_Optimized: # A[i] = A[i/2] + 1; lw $t0, 0($gp) # fetch i srl $t1, $t0, 1 # i/2 sll $t1, $t1, 2 # turn i/2 into a byte offset (*4) add $t1, $gp, $t1 # &A[i/2] - 28 lw $t1, 28($t1) # fetch A[i/2] addi $t1, $t1, 1 # A[i/2] + 1 sll $t2, $t0, 2 # turn i into a byte offset add $t2, $t2, $gp # &A[i] - 28 sw $t1, 28($t2) # A[i] = ... # A[i+1] = -1; addi $t1, $zero, -1 # -1 sw $t1, 32($t2) # A[i+1] = -1
#include <iostream> #include <stack> #include <map> #include <string> namespace briqsvm { struct Briq { char annot; char sub_annot; short bucket_index_L; short bucket_index_G; int briq_index_L; int briq_index_G; Briq(char an1, char an2) { set_defalut(an1, an2, 0, 0, 0, 0); } Briq(char an1, char an2, short bcidx1, short bcidx2, int bridx1, int bridx2) { set_defalut(an1, an2, bcidx1, bcidx2, bridx1, bridx2); } void set_defalut(char an1, char an2, short bcidx1, short bcidx2, int bridx1, int bridx2) { annot = an1; sub_annot = an2; bucket_index_L = bcidx1; bucket_index_G = bcidx2; briq_index_L = bridx1; briq_index_G = bridx2; } std::string to_s() { if (annot == '~') { return "(N)"; } else if (annot == 'N') { return ""; } std::string annot_str {annot}; return "annot is [" + annot_str + "]"; } }; class Bucket { std::stack<Briq> briqs; public: void push(Briq b) { briqs.push(b); } Briq top() { return briqs.top(); } }; class Baseplate { std::map<short, Bucket> buckets; public: Baseplate() { buckets[0] = Bucket(); auto N = Briq('N', 0); buckets[0].push(N); buckets[-1] = Bucket(); auto IP = Briq('~', 0); buckets[-1].push(IP); } Bucket get_bucket(short bucket_index) { return buckets[bucket_index]; } }; } int main() { std::cout << "hello, BriqsVM!" << std::endl; auto bp = briqsvm::Baseplate(); while(true) { std::string a; std::cout << "@|| "; std::cin >> a; if (a == "@@@") { std::cout << "bye. " << std::endl; break; } else { std::cout << "you typed: " << a << std::endl; std::cout << "[FFFF]" << bp.get_bucket(-1).top().to_s() << std::endl; std::cout << "[0000]" << bp.get_bucket(0).top().to_s() << std::endl; } } }
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "quiche/http2/decoder/payload_decoders/ping_payload_decoder.h" #include <stddef.h> #include "quiche/http2/decoder/http2_frame_decoder_listener.h" #include "quiche/http2/http2_constants.h" #include "quiche/http2/test_tools/frame_parts.h" #include "quiche/http2/test_tools/frame_parts_collector.h" #include "quiche/http2/test_tools/http2_frame_builder.h" #include "quiche/http2/test_tools/http2_random.h" #include "quiche/http2/test_tools/http2_structures_test_util.h" #include "quiche/http2/test_tools/payload_decoder_base_test_util.h" #include "quiche/http2/test_tools/random_decoder_test.h" #include "quiche/common/platform/api/quiche_logging.h" #include "quiche/common/platform/api/quiche_test.h" namespace http2 { namespace test { class PingPayloadDecoderPeer { public: static constexpr Http2FrameType FrameType() { return Http2FrameType::PING; } // Returns the mask of flags that affect the decoding of the payload (i.e. // flags that that indicate the presence of certain fields or padding). static constexpr uint8_t FlagsAffectingPayloadDecoding() { return 0; } }; namespace { struct Listener : public FramePartsCollector { void OnPing(const Http2FrameHeader& header, const Http2PingFields& ping) override { QUICHE_VLOG(1) << "OnPing: " << header << "; " << ping; StartAndEndFrame(header)->OnPing(header, ping); } void OnPingAck(const Http2FrameHeader& header, const Http2PingFields& ping) override { QUICHE_VLOG(1) << "OnPingAck: " << header << "; " << ping; StartAndEndFrame(header)->OnPingAck(header, ping); } void OnFrameSizeError(const Http2FrameHeader& header) override { QUICHE_VLOG(1) << "OnFrameSizeError: " << header; FrameError(header)->OnFrameSizeError(header); } }; class PingPayloadDecoderTest : public AbstractPayloadDecoderTest<PingPayloadDecoder, PingPayloadDecoderPeer, Listener> { protected: Http2PingFields RandPingFields() { Http2PingFields fields; test::Randomize(&fields, RandomPtr()); return fields; } }; // Confirm we get an error if the payload is not the correct size to hold // exactly one Http2PingFields. TEST_F(PingPayloadDecoderTest, WrongSize) { auto approve_size = [](size_t size) { return size != Http2PingFields::EncodedSize(); }; Http2FrameBuilder fb; fb.Append(RandPingFields()); fb.Append(RandPingFields()); fb.Append(RandPingFields()); EXPECT_TRUE(VerifyDetectsFrameSizeError(0, fb.buffer(), approve_size)); } TEST_F(PingPayloadDecoderTest, Ping) { for (int n = 0; n < 100; ++n) { Http2PingFields fields = RandPingFields(); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::PING, RandFlags() & ~Http2FrameFlag::ACK, RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptPing(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } TEST_F(PingPayloadDecoderTest, PingAck) { for (int n = 0; n < 100; ++n) { Http2PingFields fields; Randomize(&fields, RandomPtr()); Http2FrameBuilder fb; fb.Append(fields); Http2FrameHeader header(fb.size(), Http2FrameType::PING, RandFlags() | Http2FrameFlag::ACK, RandStreamId()); set_frame_header(header); FrameParts expected(header); expected.SetOptPing(fields); EXPECT_TRUE(DecodePayloadAndValidateSeveralWays(fb.buffer(), expected)); } } } // namespace } // namespace test } // namespace http2
.data tam: .word 14 datos: .word 2, 4, 2, 8, -2, 4, 2, -7, 8, 43, -5, -45, 3, 4 min: .word 0 .text main: lw $11, tam($0) lw $12, min($0) addi $13, $0, 0 ini: beq $11, $0, fin addi $11, $11, -1 sll $15, $13, 2 lw $14, datos($15) addi $13, $13, 1 ble $12, $14, no addi $12, $14, 0 no: j ini fin: sw $12, min($0) li $20, 10 syscall
############################################################################### # Copyright 2019 Intel Corporation # All Rights Reserved. # # If this software was obtained under the Intel Simplified Software License, # the following terms apply: # # The source code, information and material ("Material") contained herein is # owned by Intel Corporation or its suppliers or licensors, and title to such # Material remains with Intel Corporation or its suppliers or licensors. The # Material contains proprietary information of Intel or its suppliers and # licensors. The Material is protected by worldwide copyright laws and treaty # provisions. No part of the Material may be used, copied, reproduced, # modified, published, uploaded, posted, transmitted, distributed or disclosed # in any way without Intel's prior express written permission. No license under # any patent, copyright or other intellectual property rights in the Material # is granted to or conferred upon you, either expressly, by implication, # inducement, estoppel or otherwise. Any license under such intellectual # property rights must be express and approved by Intel in writing. # # Unless otherwise agreed by Intel in writing, you may not remove or alter this # notice or any other notice embedded in Materials by Intel or Intel's # suppliers or licensors in any way. # # # If this software was obtained under the Apache License, Version 2.0 (the # "License"), the following terms apply: # # You may not use this file except in compliance with the License. You may # obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### .section .note.GNU-stack,"",%progbits .text .p2align 4, 0x90 .globl cpAdd_BNU .type cpAdd_BNU, @function cpAdd_BNU: push %ebp mov %esp, %ebp push %ebx push %esi push %edi movl (12)(%ebp), %eax movl (16)(%ebp), %ebx movl (8)(%ebp), %edx movl (20)(%ebp), %edi shl $(2), %edi xor %ecx, %ecx pandn %mm0, %mm0 .p2align 4, 0x90 .Lmain_loopgas_1: movd (%ecx,%eax), %mm1 movd (%ebx,%ecx), %mm2 paddq %mm1, %mm0 paddq %mm2, %mm0 movd %mm0, (%edx,%ecx) pshufw $(254), %mm0, %mm0 add $(4), %ecx cmp %edi, %ecx jl .Lmain_loopgas_1 movd %mm0, %eax emms pop %edi pop %esi pop %ebx pop %ebp ret .Lfe1: .size cpAdd_BNU, .Lfe1-(cpAdd_BNU)
#include "pch.h" #include "pb.h" #include "control.h" #include "fullscrn.h" #include "high_score.h" #include "pinball.h" #include "proj.h" #include "render.h" #include "loader.h" #include "midi.h" #include "nudge.h" #include "options.h" #include "timer.h" #include "winmain.h" #include "Sound.h" #include "TBall.h" #include "TDemo.h" #include "TEdgeSegment.h" #include "TLightGroup.h" #include "TPlunger.h" #include "TTableLayer.h" #include "GroupData.h" #include "partman.h" #include "score.h" #include "TPinballTable.h" #include "TTextBox.h" #include "wii_input.h" TPinballTable* pb::MainTable = nullptr; DatFile* pb::record_table = nullptr; int pb::time_ticks = 0, pb::demo_mode = 0, pb::game_mode = 2; float pb::mode_countdown_, pb::time_now = 0, pb::time_next = 0, pb::ball_speed_limit, pb::time_ticks_remainder = 0; high_score_struct pb::highscore_table[5]; bool pb::FullTiltMode = false, pb::cheat_mode = false; int pb::init() { float projMat[12], zMin = 0, zScaler = 0; auto dataFilePath = pinball::make_path_name(winmain::DatFileName); record_table = partman::load_records(dataFilePath.c_str(), FullTiltMode); auto useBmpFont = 0; pinball::get_rc_int(158, &useBmpFont); if (useBmpFont) score::load_msg_font("pbmsg_ft"); if (!record_table) return 1; auto plt = (ColorRgba*)record_table->field_labeled("background", FieldTypes::Palette); gdrv::display_palette(plt); auto backgroundBmp = record_table->GetBitmap(record_table->record_labeled("background")); auto cameraInfoId = record_table->record_labeled("camera_info") + fullscrn::GetResolution(); auto cameraInfo = (float*)record_table->field(cameraInfoId, FieldTypes::FloatArray); /*Full tilt: table size depends on resolution*/ auto resInfo = &fullscrn::resolution_array[fullscrn::GetResolution()]; if (cameraInfo) { memcpy(&projMat, cameraInfo, sizeof(float) * 4 * 3); cameraInfo += 12; auto projCenterX = resInfo->TableWidth * 0.5f; auto projCenterY = resInfo->TableHeight * 0.5f; auto projD = cameraInfo[0]; proj::init(projMat, projD, projCenterX, projCenterY); zMin = cameraInfo[1]; zScaler = cameraInfo[2]; } render::init(nullptr, zMin, zScaler, resInfo->TableWidth, resInfo->TableHeight); gdrv::copy_bitmap( render::vscreen, backgroundBmp->Width, backgroundBmp->Height, backgroundBmp->XPosition, backgroundBmp->YPosition, backgroundBmp, 0, 0); loader::loadfrom(record_table); if (pinball::quickFlag) mode_change(1); else mode_change(3); time_ticks = 0; timer::init(150); score::init(); MainTable = new TPinballTable(); high_score::read(highscore_table); ball_speed_limit = MainTable->BallList.at(0)->Offset * 200.0f; return 0; } int pb::uninit() { score::unload_msg_font(); loader::unload(); delete record_table; high_score::write(highscore_table); delete MainTable; MainTable = nullptr; timer::uninit(); render::uninit(); return 0; } void pb::reset_table() { if (MainTable) MainTable->Message(1024, 0.0); } void pb::firsttime_setup() { render::update(); } void pb::mode_change(int mode) { switch (mode) { case 1: if (demo_mode) { winmain::LaunchBallEnabled = false; winmain::HighScoresEnabled = false; winmain::DemoActive = true; if (MainTable) { if (MainTable->Demo) MainTable->Demo->ActiveFlag = 1; } } else { winmain::LaunchBallEnabled = true; winmain::HighScoresEnabled = true; winmain::DemoActive = false; if (MainTable) { if (MainTable->Demo) MainTable->Demo->ActiveFlag = 0; } } break; case 2: winmain::LaunchBallEnabled = false; if (!demo_mode) { winmain::HighScoresEnabled = true; winmain::DemoActive = false; } if (MainTable && MainTable->LightGroup) MainTable->LightGroup->Message(29, 1.4f); break; case 3: case 4: winmain::LaunchBallEnabled = false; winmain::HighScoresEnabled = false; mode_countdown_ = 5000.f; break; } game_mode = mode; } void pb::toggle_demo() { if (demo_mode) { demo_mode = 0; MainTable->Message(1024, 0.0); mode_change(2); pinball::MissTextBox->Clear(); auto text = pinball::get_rc_string(24, 0); pinball::InfoTextBox->Display(text, -1.0); } else { replay_level(1); } } void pb::replay_level(int demoMode) { demo_mode = demoMode; mode_change(1); if (options::Options.Music) midi::play_pb_theme(); MainTable->Message(1014, static_cast<float>(options::Options.Players)); } void pb::ballset(float dx, float dy) { // dx and dy are normalized to window, ideally in [-1, 1] static constexpr float sensitivity = 7000; TBall* ball = MainTable->BallList.at(0); ball->Acceleration.X = dx * sensitivity; ball->Acceleration.Y = dy * sensitivity; ball->Speed = maths::normalize_2d(&ball->Acceleration); } void pb::frame(float dtMilliSec) { if (dtMilliSec > 100) dtMilliSec = 100; if (dtMilliSec <= 0) return; float dtSec = dtMilliSec * 0.001f; if (!mode_countdown(dtMilliSec)) { time_next = time_now + dtSec; timed_frame(time_now, dtSec, true); time_now = time_next; dtMilliSec += time_ticks_remainder; auto dtWhole = static_cast<int>(dtMilliSec); time_ticks_remainder = dtMilliSec - static_cast<float>(dtWhole); time_ticks += dtWhole; if (nudge::nudged_left || nudge::nudged_right || nudge::nudged_up) { nudge::nudge_count = dtSec * 4.0f + nudge::nudge_count; } else { auto nudgeDec = nudge::nudge_count - dtSec; if (nudgeDec <= 0.0f) nudgeDec = 0.0; nudge::nudge_count = nudgeDec; } timer::check(); render::update(); score::update(MainTable->CurScoreStruct); if (!MainTable->TiltLockFlag) { if (nudge::nudge_count > 0.5f) { pinball::InfoTextBox->Display(pinball::get_rc_string(25, 0), 2.0); } if (nudge::nudge_count > 1.0f) MainTable->tilt(time_now); } } } void pb::timed_frame(float timeNow, float timeDelta, bool drawBalls) { vector_type vec1{}, vec2{}; for (auto ball : MainTable->BallList) { if (ball->ActiveFlag != 0) { auto collComp = ball->CollisionComp; if (collComp) { ball->TimeDelta = timeDelta; collComp->FieldEffect(ball, &vec1); } else { if (MainTable->ActiveFlag) { vec2.X = 0.0; vec2.Y = 0.0; vec2.Z = 0.0; TTableLayer::edge_manager->FieldEffects(ball, &vec2); vec2.X = vec2.X * timeDelta; vec2.Y = vec2.Y * timeDelta; ball->Acceleration.X = ball->Speed * ball->Acceleration.X; ball->Acceleration.Y = ball->Speed * ball->Acceleration.Y; maths::vector_add(&ball->Acceleration, &vec2); ball->Speed = maths::normalize_2d(&ball->Acceleration); ball->InvAcceleration.X = ball->Acceleration.X == 0.0f ? 1.0e9f : 1.0f / ball->Acceleration.X; ball->InvAcceleration.Y = ball->Acceleration.Y == 0.0f ? 1.0e9f : 1.0f / ball->Acceleration.Y; } auto timeDelta2 = timeDelta; auto timeNow2 = timeNow; for (auto index = 10; timeDelta2 > 0.000001f && index; --index) { auto time = collide(timeNow2, timeDelta2, ball); timeDelta2 -= time; timeNow2 += time; } } } } if (drawBalls) { for (auto ball : MainTable->BallList) { if (ball->ActiveFlag) ball->Repaint(); } } } void pb::window_size(int* width, int* height) { *width = fullscrn::resolution_array[fullscrn::GetResolution()].TableWidth; *height = fullscrn::resolution_array[fullscrn::GetResolution()].TableHeight; } void pb::pause_continue() { winmain::single_step ^= true; pinball::InfoTextBox->Clear(); pinball::MissTextBox->Clear(); if (winmain::single_step) { if (MainTable) MainTable->Message(1008, time_now); pinball::InfoTextBox->Display(pinball::get_rc_string(22, 0), -1.0); midi::music_stop(); Sound::Deactivate(); } else { if (MainTable) MainTable->Message(1009, 0.0); if (!demo_mode) { char* text; float textTime; if (game_mode == 2) { textTime = -1.0; text = pinball::get_rc_string(24, 0); } else { textTime = 5.0; text = pinball::get_rc_string(23, 0); } pinball::InfoTextBox->Display(text, textTime); } if (options::Options.Music && !winmain::single_step) midi::play_pb_theme(); Sound::Activate(); } } void pb::loose_focus() { if (MainTable) MainTable->Message(1010, time_now); } void pb::keyup(uint32_t wiiButton, uint32_t gcButton) { if (game_mode != 1 || winmain::single_step || demo_mode) return; if ((wiiButton & WPAD_NUNCHUK_BUTTON_Z) || (gcButton & PAD_TRIGGER_L)) { MainTable->Message(1001, time_now); } if ((wiiButton & WPAD_BUTTON_B) || (gcButton & PAD_TRIGGER_R)) { MainTable->Message(1003, time_now); } if ((wiiButton & WPAD_BUTTON_A) || (gcButton & PAD_BUTTON_A)) { MainTable->Message(1005, time_now); } if ((wiiButton & WPAD_BUTTON_RIGHT) || (gcButton & PAD_BUTTON_RIGHT)) { nudge::un_nudge_right(0, nullptr); } else if ((wiiButton & WPAD_BUTTON_LEFT) || (gcButton & PAD_BUTTON_LEFT)) { nudge::un_nudge_left(0, nullptr); } else if ((wiiButton & WPAD_BUTTON_UP) || (gcButton & PAD_BUTTON_UP)) { nudge::un_nudge_up(0, nullptr); } } void pb::keydown(uint32_t wiiButton, uint32_t gcButton) { if (winmain::single_step || demo_mode) return; if (game_mode != 1) { mode_countdown(-1.f); return; } // control::pbctrl_bdoor_controller(static_cast<char>(key)); if ((wiiButton & WPAD_NUNCHUK_BUTTON_Z) || (gcButton & PAD_TRIGGER_L)) { MainTable->Message(1000, time_now); } if ((wiiButton & WPAD_BUTTON_B) || (gcButton & PAD_TRIGGER_R)) { MainTable->Message(1002, time_now); } if ((wiiButton & WPAD_BUTTON_A) || (gcButton & PAD_BUTTON_A)) { MainTable->Message(1004, time_now); } if ((wiiButton & WPAD_BUTTON_RIGHT) || (gcButton & PAD_BUTTON_RIGHT)) { if (!MainTable->TiltLockFlag) nudge::nudge_right(); } if ((wiiButton & WPAD_BUTTON_LEFT) || (gcButton & PAD_BUTTON_LEFT)) { if (!MainTable->TiltLockFlag) nudge::nudge_left(); } if ((wiiButton & WPAD_BUTTON_UP) || (gcButton & PAD_BUTTON_UP)) { if (!MainTable->TiltLockFlag) nudge::nudge_up(); } // if (cheat_mode) // { // switch (key) // { // case 'b': // TBall *ball; // if (MainTable->BallList.empty()) // { // ball = new TBall(MainTable); // } // else // { // for (auto index = 0u;;) // { // ball = MainTable->BallList.at(index); // if (!ball->ActiveFlag) // break; // ++index; // if (index >= MainTable->BallList.size()) // { // ball = new TBall(MainTable); // break; // } // } // } // ball->Position.X = 1.0; // ball->ActiveFlag = 1; // ball->Position.Z = ball->Offset; // ball->Position.Y = 1.0; // ball->Acceleration.Z = 0.0; // ball->Acceleration.Y = 0.0; // ball->Acceleration.X = 0.0; // break; // case 'h': // char String1[200]; // strncpy(String1, pinball::get_rc_string(26, 0), sizeof String1 - 1); // high_score::show_and_set_high_score_dialog(highscore_table, 1000000000, 1, String1); // break; // case 'r': // control::cheat_bump_rank(); // break; // case 's': // MainTable->AddScore(static_cast<int>(RandFloat() * 1000000.0f)); // break; // case SDLK_F12: // MainTable->port_draw(); // break; // } // } } int pb::mode_countdown(float time) { if (!game_mode || game_mode <= 0) return 1; if (game_mode > 2) { if (game_mode == 3) { mode_countdown_ -= time; if (mode_countdown_ < 0.f || time < 0.f) mode_change(4); } else if (game_mode == 4) { mode_countdown_ -= time; if (mode_countdown_ < 0.f || time < 0.f) mode_change(1); } return 1; } return 0; } void pb::launch_ball() { MainTable->Plunger->Message(1017, 0.0f); } void pb::end_game() { int scores[4]{}; int scoreIndex[4]{}; char String1[200]; mode_change(2); int playerCount = MainTable->PlayerCount; score_struct_super* scorePtr = MainTable->PlayerScores; for (auto index = 0; index < playerCount; ++index) { scores[index] = scorePtr->ScoreStruct->Score; scoreIndex[index] = index; ++scorePtr; } for (auto i = 0; i < playerCount; ++i) { for (auto j = i + 1; j < playerCount; ++j) { if (scores[j] > scores[i]) { int score = scores[j]; scores[j] = scores[i]; scores[i] = score; int index = scoreIndex[j]; scoreIndex[j] = scoreIndex[i]; scoreIndex[i] = index; } } } if (!demo_mode && !MainTable->CheatsUsed) { for (auto i = 0; i < playerCount; ++i) { int position = high_score::get_score_position(highscore_table, scores[i]); if (position >= 0) { strncpy(String1, pinball::get_rc_string(scoreIndex[i] + 26, 0), sizeof String1 - 1); high_score::show_and_set_high_score_dialog(highscore_table, scores[i], position, String1); } } } } void pb::high_scores() { high_score::show_high_score_dialog(highscore_table); } void pb::tilt_no_more() { if (MainTable->TiltLockFlag) pinball::InfoTextBox->Clear(); MainTable->TiltLockFlag = 0; nudge::nudge_count = -2.0; } bool pb::chk_highscore() { if (demo_mode) return false; int playerIndex = MainTable->PlayerCount - 1; if (playerIndex < 0) return false; for (int i = playerIndex; high_score::get_score_position(highscore_table, MainTable->PlayerScores[i].ScoreStruct->Score) < 0; --i) { if (--playerIndex < 0) return false; } return true; } float pb::collide(float timeNow, float timeDelta, TBall* ball) { ray_type ray{}; vector_type positionMod{}; if (ball->ActiveFlag && !ball->CollisionComp) { if (ball_speed_limit < ball->Speed) ball->Speed = ball_speed_limit; auto maxDistance = timeDelta * ball->Speed; ball->TimeDelta = timeDelta; ball->RayMaxDistance = maxDistance; ball->TimeNow = timeNow; ray.Origin.X = ball->Position.X; ray.Origin.Y = ball->Position.Y; ray.Origin.Z = ball->Position.Z; ray.Direction.X = ball->Acceleration.X; ray.Direction.Y = ball->Acceleration.Y; ray.Direction.Z = ball->Acceleration.Z; ray.MaxDistance = maxDistance; ray.FieldFlag = ball->FieldFlag; ray.TimeNow = timeNow; ray.TimeDelta = timeDelta; ray.MinDistance = 0.0020000001f; TEdgeSegment* edge = nullptr; auto distance = TTableLayer::edge_manager->FindCollisionDistance(&ray, ball, &edge); ball->EdgeCollisionCount = 0; if (distance >= 1000000000.0f) { maxDistance = timeDelta * ball->Speed; ball->RayMaxDistance = maxDistance; positionMod.X = maxDistance * ball->Acceleration.X; positionMod.Y = maxDistance * ball->Acceleration.Y; positionMod.Z = 0.0; maths::vector_add(&ball->Position, &positionMod); } else { edge->EdgeCollision(ball, distance); if (ball->Speed > 0.000000001f) return fabs(distance / ball->Speed); } } return timeDelta; } void pb::PushCheat(const std::string& cheat) { for (auto ch : cheat) control::pbctrl_bdoor_controller(ch); }
; A145610: Denominator of the polynomial A_l(x) = Sum_{d=1..l-1} x^(l-d)/d for index l=2n+1 evaluated at x=1. ; Submitted by Jon Maiga ; 2,12,20,280,2520,27720,360360,720720,4084080,15519504,5173168,356948592,8923714800,80313433200,2329089562800,144403552893600,13127595717600,13127595717600,485721041551200,485721041551200 mul $0,2 add $0,1 seq $0,2805 ; Denominators of harmonic numbers H(n) = Sum_{i=1..n} 1/i.
COMMENT @/******************************************************** Copyright (C) Dirk Lausecker -- All Rights Reserved PROJECT: BestSound Treiber DATEI: bsnwav.asm AUTOR: Dirk Lausecker REVISION HISTORY: Name Datum Beschreibung ---- ----- ------------ DL 06.10.98 Init DL 20.02.2000 Ableitung BSNWAV.ASM DL 02.03.2000 bsOptions Bit 0 definiert DL 09.03.2000 bsSingle DL 13.03.2000 Ableitung BSD8ST DL 16.03.2000 bsSingle abgeschafft DL 16.08.2000 Translation for ND Routines: Name Description ---- ----------- BSDNWGetStatus returns bsStatus and dacStatus BSDNWGetAIState returns aiStatus BSDNWStartPlay Start playing BSNWISR ISR for NewWave-PLAY Description: Totally new concept for playing Sampledata without Soundlibrary and Streamlibrary bsOptions: Bit 0: TRUE --> Buffer will be erased after playing *****************************************************************/@ BSNW_STATE_IDLE equ 0 ; soundcard is idle ; States 1,2 and 5 are reserved for recording Recording BSNW_PLAY_PREPARE equ 3 ; NewWave-Play Prepare phase BSNW_PLAY_RUN equ 4 ; NewWave-Play active ;///////////////////////////////// ; Globals ;///////////////////////////////// idata segment bsOptions byte 1 ; Bit 0 -> Buffer will be erased ; by ISR after playing bsPause byte 0 ; 1 = Pause 2 = Restart idata ends ;=========================================================== LoadableCode segment resource ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSDNWSetPause ; ; Pause Mode ; ; IN: cl Mode 0 = request mode ; 1 = PAUSE ; 2 = RESTART ; ; OUT: ch current mode ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSDNWSetPause proc far uses ax,bx,dx,ds .enter mov ax,segment dgroup mov ds,ax mov ch,0 ; default value tst ds:[dacStatus] ; old WAV-Output ? jnz done mov al,ds:[bsStatus] ; NewWave Play cmp al,BSNW_PLAY_RUN ; running ? jnz done ;---------------------------- ; PAUSE / RESTART ;---------------------------- mov ch,ds:[bsPause] ; current mode cmp cl,ch ; new mode equal old mode ? jz done ; yes cmp ch,1 ; current mode = PAUSE ? jz nopause ; yes cmp cl,1 ; new mode = PAUSE ? jnz nopause ; nein ; ; PAUSE ; SBDDACWriteDSP DSP_DMA_HALT,0 mov ch,1 mov ds:[bsPause],ch jmp done ; ; PAUSE already active ; nopause: cmp cl,2 ; new mode = RESTART ? jnz done ; no ; ; RESTART ; SBDDACWriteDSP DSP_DMA_CONTINUE,0 mov ch,2 mov ds:[bsPause],ch done: .leave ret BSDNWSetPause endp ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSDNWGetStatus ; ; returns dacStatus/bsStatus ; ; IN: - ; ; OUT: cl bsStatus ; ch dacStatus ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSDNWGetStatus proc far uses ax,bx,dx,ds .enter mov ax,segment dgroup mov ds,ax mov ch,ds:[dacStatus] mov cl,ds:[bsStatus] .leave ret BSDNWGetStatus endp ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSDNWStartPlay ; ; Start WAV-Output ; Top-Level call other subroutines ; ; ; OUT: cx 0 = OK ; 1 = problems ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSDNWStartPlay proc far uses ax,bx,dx,di,ds .enter mov ax,segment dgroup mov ds,ax ;------------------- ; dacStatus = idle ? ;------------------- tst ds:[dacStatus] ; DAC active ? jnz error ; yes mov ds:[bsStatus],BSNW_PLAY_PREPARE clr ds:[bsRecDataFlag] ; clear DataFlag ;------------------- ; Mono / Stereo ;------------------- mov ah,DSP_DMA_PCM_AI_MONO_LOW mov al,ds:[bsChannels] ; get channels cmp al,2 ; Stereo ? jnz set_bef ; no ; ; Stereomode ; mov al,MIXER_OUTPUT mov dx,ds:[basePortAddress] add dx,4 ; Mixer Address Port out dx,al inc dx in al,dx or al,00000010b out dx,al mov ah,DSP_DMA_PCM_AI_HIGH ; DSP-command set_bef: mov ds:[DSPFormatCommand],ah ;------------------- ; DSP timeconstant ;------------------- call BSDRecSetTimeConst ;------------------- ; Mono / Stereo ;------------------- mov al,ds:[bsChannels] cmp al,2 ; Stereo ? jnz set_size ; no ; ; Filterstatus ; mov al,MIXER_OUTPUT mov dx,ds:[basePortAddress] add dx,4 ; Mixer Address Port out dx,al inc dx in al,dx mov ds:[filterState],al ; store in tempbuffer or al,00100000b ; out dx,al mov ds:[hsFlag],1 ; set Highspeedflag ;------------------------ ; DSP Blocktransfersize ;------------------------ set_size: call BSDRecSetTransferSize ;------------------------ ; Start AutoInit Transfer ;------------------------ mov ds:[bsStatus],BSNW_PLAY_RUN call BSDNWStartAI jc error ; error ! mov cx,0 ; no error jmp done ; --> End ;------------------------ ; handling errors ;------------------------ error1: call BSDRecFreeBuffer ; release buffer ;------------------------ ; E N D ;------------------------ error: mov ds:[bsStatus],BS_STATE_IDLE mov cx,1 clc ; CY = 1 done: .leave ret BSDNWStartPlay endp ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSDNWStartAI ; ; Start AutoInit Transfer ; for Output ; ; ; IN: - ; ; OUT: CY TRUE = error ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSDNWStartAI proc near uses ax,bx,cx,dx,di,ds .enter mov ax,segment dgroup mov ds,ax clr ds:[bsRecDataHalf] clr ds:[bsRecDataFlag] mov cl,ds:[DSPFormatCommand] SBDDACWriteDSP cl, 0 ; AutoInit Output clc .leave ret BSDNWStartAI endp ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSDNWGetAIState ; ; Returns Statusvar. Autoinittransfer ; ; ; IN: ch >0 -> set bsOptions (cl) ; cl bsOptions ; ; OUT: cl bsRecDataFlag ; ch bsRecDataHalf ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSDNWGetAIState proc far uses ax,bx,dx,ds .enter mov ax,segment dgroup mov ds,ax ;------------------- ; set bsOptions ;------------------- tst ch ; set bsOptions ? jz noset ; nein mov ds:[bsOptions],cl ; ja noset: mov ch,ds:[bsRecDataHalf] mov cl,ds:[bsRecDataFlag] .leave ret BSDNWGetAIState endp LoadableCode ends ResidentCode segment resource ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSNWISR ; ; ISR for NewWavePlay ; ; Will be called when the buffer ; must be filled with new data ; ; IN: (glob) bsOptions ; ds dgroup ; ; OUT: - ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSNWISR proc far uses ax,cx,ds,di,es .enter ;----------------------------- ; erase the old data ;----------------------------- kill_half: tst ds:[bufferO2] ; Buffer existent ? jz done ; no (zero len) mov di,0 ; Offsetpointer mov cx,ds:[bufferO2] mov ah,ds:[bsOptions] test ah,01h ; Flag (Bit0) ? jz done ; no, don't erase ! mov al,ds:[bsRecDataHalf] tst al ; lower half ? jz firstbuf mov di,cx ; higher half firstbuf: mov ax,ds:[bufferSegment] mov es,ax ; Segmentaddress mov ah,080h next: mov es:[di],ah ; erase Buffer inc di dec cx jnz next done: inc ds:[bsRecDataFlag] mov al,ds:[bsRecDataHalf] xor al,01h mov ds:[bsRecDataHalf],al done2: .leave ret BSNWISR endp ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% ; ; BSResetMode ; ; ; IN: (glob) bsStatus ; ds dgroup ; ; OUT: - ; ;%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% BSResetMode proc near uses ax,cx,dx,ds,di .enter mov dx,ds:[basePortAddress] add dx,4 ; Mixer Address Port ;------------------------ ; Recording ;------------------------ mov al,ds:[bsStatus] cmp al,BSREC_STATE_RUN ; Recording ? jnz new_wave ; no ; ; Restore Inputfilter ; mov al,MIXER_FILTER ; Inputfilter out dx,al inc dx mov al,ds:[filterState] ; restore old value from temp buffer out dx,al ; ; Reset to Mono ; SBDDACWriteDSP DSP_MONO_MODE, 0 jmp short done ;------------------------ ; NewWave-Play ;------------------------ new_wave: ; ; Restore Filter ; mov al,MIXER_OUTPUT ; Inputfilter (0E) out dx,al inc dx mov al,ds:[filterState] ; restore old value from temp buffer out dx,al ; ; Reset to Mono ; dec dx ; Mixer Address Port (224) mov al,MIXER_OUTPUT ; Inputfilter (0E) out dx,al inc dx in al,dx and al,11111101b out dx,al done: .leave ret BSResetMode endp ResidentCode ends
// Copyright 2018 The Beam Team // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #define LOG_VERBOSE_ENABLED 1 #include "utility/logger.h" #include "service.h" #include <boost/program_options.hpp> #include <boost/filesystem.hpp> #include <boost/algorithm/string/trim.hpp> #include <map> #include <queue> #include <cstdio> #include "utility/cli/options.h" #include "utility/helpers.h" #include "utility/io/timer.h" #include "utility/io/json_serializer.h" #include "utility/string_helpers.h" #include "utility/log_rotation.h" #include "wallet/api/api_handler.h" #include "wallet/core/wallet_db.h" #include "wallet/core/wallet_network.h" #include "wallet/core/simple_transaction.h" #include "keykeeper/local_private_key_keeper.h" #include <boost/uuid/uuid_generators.hpp> #include "nlohmann/json.hpp" #include "version.h" #include "keykeeper/wasm_key_keeper.h" #include "pipe.h" #include "websocket_server.h" using json = nlohmann::json; static const unsigned LOG_ROTATION_PERIOD = 3 * 60 * 60 * 1000; // 3 hours static const size_t PACKER_FRAGMENTS_SIZE = 4096; using namespace beam; using namespace beam::wallet; namespace beam::wallet { io::Address node_addr; WalletServiceApi::WalletServiceApi(IWalletServiceApiHandler& handler, ACL acl) : WalletApi(handler, acl) { #define REG_FUNC(api, name, writeAccess) \ _methods[name] = {BIND_THIS_MEMFN(on##api##Message), writeAccess}; WALLET_SERVICE_API_METHODS(REG_FUNC) #undef REG_FUNC }; IWalletServiceApiHandler& WalletServiceApi::getHandler() const { return static_cast<IWalletServiceApiHandler&>(_handler); } void WalletServiceApi::onCreateWalletMessage(const JsonRpcId& id, const nlohmann::json& params) { CreateWallet createWallet; if (existsJsonParam(params, "pass")) { createWallet.pass = params["pass"].get<std::string>(); } else throw jsonrpc_exception{ ApiError::InvalidJsonRpc, "'pass' parameter must be specified.", id }; if (existsJsonParam(params, "ownerkey")) { createWallet.ownerKey = params["ownerkey"].get<std::string>(); } else throw jsonrpc_exception{ ApiError::InvalidJsonRpc, "'ownerkey' parameter must be specified.", id }; getHandler().onMessage(id, createWallet); } void WalletServiceApi::onOpenWalletMessage(const JsonRpcId& id, const nlohmann::json& params) { OpenWallet openWallet; if (existsJsonParam(params, "pass")) { openWallet.pass = params["pass"].get<std::string>(); } else throw jsonrpc_exception{ ApiError::InvalidJsonRpc, "'pass' parameter must be specified.", id }; if (existsJsonParam(params, "id")) { openWallet.id = params["id"].get<std::string>(); } else throw jsonrpc_exception{ ApiError::InvalidJsonRpc, "'id' parameter must be specified.", id }; getHandler().onMessage(id, openWallet); } void WalletServiceApi::onPingMessage(const JsonRpcId& id, const nlohmann::json& params) { getHandler().onMessage(id, Ping{}); } void WalletServiceApi::onReleaseMessage(const JsonRpcId& id, const nlohmann::json& params) { getHandler().onMessage(id, Release{}); } void WalletServiceApi::getResponse(const JsonRpcId& id, const CreateWallet::Response& res, json& msg) { msg = json { {JsonRpcHrd, JsonRpcVerHrd}, {"id", id}, {"result", res.id} }; } void WalletServiceApi::getResponse(const JsonRpcId& id, const OpenWallet::Response& res, json& msg) { msg = json { {JsonRpcHrd, JsonRpcVerHrd}, {"id", id}, {"result", res.session} }; } void WalletServiceApi::getResponse(const JsonRpcId& id, const Ping::Response& res, json& msg) { msg = json { {JsonRpcHrd, JsonRpcVerHrd}, {"id", id}, {"result", "pong"} }; } void WalletServiceApi::getResponse(const JsonRpcId& id, const Release::Response& res, json& msg) { msg = json { {JsonRpcHrd, JsonRpcVerHrd}, {"id", id}, {"result", "done"} }; } } namespace { void fail(boost::system::error_code ec, char const* what) { LOG_ERROR() << what << ": " << ec.message(); } class WalletApiServer : public WebSocketServer { public: WalletApiServer(io::Reactor::Ptr reactor, uint16_t port, const std::string& allowedOrigin) : WebSocketServer(reactor, port, [this, reactor] (auto&& func) { return std::make_unique<ServiceApiConnection>(func, reactor, _walletMap); }, [] () { #ifndef _WIN32 Pipe syncPipe(Pipe::SyncFileDescriptor); syncPipe.notifyListening(); #endif }, allowedOrigin) #ifndef _WIN32 , _heartbeatPipe(Pipe::HeartbeatFileDescriptor) #endif { #ifndef _WIN32 _heartbeatTimer = io::Timer::create(*reactor); _heartbeatTimer->start(Pipe::HeartbeatInterval, true, [this] () { _heartbeatPipe.notifyAlive(); }); #endif } private: #ifndef _WIN32 io::Timer::Ptr _heartbeatTimer; Pipe _heartbeatPipe; #endif private: struct WalletInfo { std::string ownerKey; std::weak_ptr<Wallet> wallet; std::weak_ptr<IWalletDB> walletDB; WalletInfo(const std::string& ownerKey, Wallet::Ptr wallet, IWalletDB::Ptr walletDB) : ownerKey(ownerKey) , wallet(wallet) , walletDB(walletDB) {} WalletInfo() = default; }; using WalletMap = std::unordered_map<std::string, WalletInfo>; WalletMap _walletMap; struct IApiConnectionHandler { virtual void serializeMsg(const json& msg) = 0; using KeyKeeperFunc = std::function<void(const json&)>; virtual void sendAsync(const json& msg, KeyKeeperFunc func) = 0; }; class WasmKeyKeeperProxy : public PrivateKeyKeeper_AsyncNotify , public std::enable_shared_from_this<WasmKeyKeeperProxy> { public: WasmKeyKeeperProxy(Key::IPKdf::Ptr ownerKdf, IApiConnectionHandler& connection, io::Reactor::Ptr reactor) : _ownerKdf(ownerKdf) , _connection(connection) , _reactor(reactor) {} virtual ~WasmKeyKeeperProxy(){} Status::Type InvokeSync(Method::get_Kdf& x) override { if (x.m_Root) { assert(_ownerKdf); x.m_pPKdf = _ownerKdf; return Status::Success; } return PrivateKeyKeeper_AsyncNotify::InvokeSync(x); } void InvokeAsync(Method::get_Kdf& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "get_kdf"}, {"params", { {"root", x.m_Root}, {"child_key_num", x.m_iChild} } } }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { ByteBuffer buf = from_base64<ByteBuffer>(msg["pub_kdf"]); ECC::HKdfPub::Packed* packed = reinterpret_cast<ECC::HKdfPub::Packed*>(&buf[0]); auto pubKdf = std::make_shared<ECC::HKdfPub>(); pubKdf->Import(*packed); x.m_pPKdf = pubKdf; } PushOut(s, h); }); } void InvokeAsync(Method::get_NumSlots& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "get_slots"} }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { x.m_Count = msg["count"]; } PushOut(s, h); }); } void InvokeAsync(Method::CreateOutput& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "create_output"}, {"params", { {"scheme", to_base64(x.m_hScheme)}, {"id", to_base64(x.m_Cid)} } } }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { x.m_pResult = from_base64<Output::Ptr>(msg["result"]); } PushOut(s, h); }); } void InvokeAsync(Method::SignReceiver& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "sign_receiver"}, {"params", { {"inputs", to_base64(x.m_vInputs)}, {"outputs", to_base64(x.m_vOutputs)}, {"kernel", to_base64(x.m_pKernel)}, {"non_conv", x.m_NonConventional}, {"peer_id", to_base64(x.m_Peer)}, {"my_id_key", to_base64(x.m_MyIDKey)} } } }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { GetMutualResult(x, msg); } PushOut(s, h); }); } void InvokeAsync(Method::SignSender& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "sign_sender"}, {"params", { {"inputs", to_base64(x.m_vInputs)}, {"outputs", to_base64(x.m_vOutputs)}, {"kernel", to_base64(x.m_pKernel)}, {"non_conv", x.m_NonConventional}, {"peer_id", to_base64(x.m_Peer)}, {"my_id_key", to_base64(x.m_MyIDKey)}, {"slot", x.m_Slot}, {"agreement", to_base64(x.m_UserAgreement)}, {"my_id", to_base64(x.m_MyID)}, {"payment_proof_sig", to_base64(x.m_PaymentProofSignature)} } } }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { if (x.m_UserAgreement == Zero) { x.m_UserAgreement = from_base64<ECC::Hash::Value>(msg["agreement"]); x.m_pKernel->m_Commitment = from_base64<ECC::Point>(msg["commitment"]); x.m_pKernel->m_Signature.m_NoncePub = from_base64<ECC::Point>(msg["pub_nonce"]); } else { GetCommonResult(x, msg); } } PushOut(s, h); }); } void InvokeAsync(Method::SignSplit& x, const Handler::Ptr& h) override { json msg = { {WalletApi::JsonRpcHrd, WalletApi::JsonRpcVerHrd}, {"id", 0}, {"method", "sign_split"}, {"params", { {"inputs", to_base64(x.m_vInputs)}, {"outputs", to_base64(x.m_vOutputs)}, {"kernel", to_base64(x.m_pKernel)}, {"non_conv", x.m_NonConventional} } } }; _connection.sendAsync(msg, [this, &x, h](const json& msg) { Status::Type s = GetStatus(msg); if (s == Status::Success) { GetCommonResult(x, msg); } PushOut(s, h); }); } static void GetMutualResult(Method::TxMutual& x, const json& msg) { x.m_PaymentProofSignature = from_base64<ECC::Signature>(msg["payment_proof_sig"]); GetCommonResult(x, msg); } static void GetCommonResult(Method::TxCommon& x, const json& msg) { auto offset = from_base64<ECC::Scalar>(msg["offset"]); x.m_kOffset.Import(offset); x.m_pKernel = from_base64<TxKernelStd::Ptr>(msg["kernel"]); } static Status::Type GetStatus(const json& msg) { return msg["status"]; } private: Key::IPKdf::Ptr _ownerKdf; IApiConnectionHandler& _connection; io::Reactor::Ptr _reactor; }; class MyApiConnection : public WalletApiHandler { public: MyApiConnection(IApiConnectionHandler* handler, IWalletData& walletData, WalletApi::ACL acl) : WalletApiHandler(walletData, acl) , _handler(handler) { } void serializeMsg(const json& msg) override { _handler->serializeMsg(msg); } private: IApiConnectionHandler* _handler; }; class ServiceApiConnection : public IWalletServiceApiHandler , private WalletApiHandler::IWalletData , public WebSocketServer::IHandler , public IApiConnectionHandler { public: ServiceApiConnection(WebSocketServer::SendMessageFunc sendFunc, io::Reactor::Ptr reactor, WalletMap& walletMap) : _apiConnection(this, *this, boost::none) , _sendFunc(sendFunc) , _reactor(reactor) , _api(*this) , _walletMap(walletMap) { assert(_sendFunc); } virtual ~ServiceApiConnection() { } // IWalletData methods IWalletDB::Ptr getWalletDB() override { assert(_walletDB); return _walletDB; } Wallet& getWallet() override { assert(_wallet); return *_wallet; } #ifdef BEAM_ATOMIC_SWAP_SUPPORT const IAtomicSwapProvider& getAtomicSwapProvider() const override { throw std::runtime_error("not supported"); } #endif // BEAM_ATOMIC_SWAP_SUPPORT void serializeMsg(const json& msg) override { _sendFunc(msg.dump()); } void sendAsync(const json& msg, KeyKeeperFunc func) override { _keeperCallbacks.push(std::move(func)); serializeMsg(msg); } void processData(const std::string& data) override { try { json msg = json::parse(data.c_str(), data.c_str() + data.size()); if (WalletApi::existsJsonParam(msg, "result")) { if (_keeperCallbacks.empty()) return; _keeperCallbacks.front()(msg["result"]); _keeperCallbacks.pop(); } else if (WalletApi::existsJsonParam(msg, "error")) { const auto& error = msg["error"]; LOG_ERROR() << "JSON RPC error id: " << error["id"] << " message: " << error["message"]; } else { // !TODO: don't forget to cache this request _api.parse(data.c_str(), data.size()); } } catch (const nlohmann::detail::exception & e) { LOG_ERROR() << "json parse: " << e.what() << "\n"; } } void onInvalidJsonRpc(const json& msg) override { _apiConnection.onInvalidJsonRpc(msg); } template<typename T> void doResponse(const JsonRpcId& id, const T& response) { json msg; _api.getResponse(id, response, msg); serializeMsg(msg); } #define MESSAGE_FUNC(api, name, _) \ void onMessage(const JsonRpcId& id, const wallet::api& data) override \ { _apiConnection.onMessage(id, data); } WALLET_API_METHODS(MESSAGE_FUNC) #undef MESSAGE_FUNC void onMessage(const JsonRpcId& id, const CreateWallet& data) override { LOG_DEBUG() << "CreateWallet(id = " << id << ")"; beam::KeyString ks; ks.SetPassword(data.pass); ks.m_sRes = data.ownerKey; std::shared_ptr<ECC::HKdfPub> ownerKdf = std::make_shared<ECC::HKdfPub>(); if(ks.Import(*ownerKdf)) { auto keyKeeper = createKeyKeeper(ownerKdf); auto dbName = generateWalletID(ownerKdf); IWalletDB::Ptr walletDB = WalletDB::init(dbName + ".db", SecString(data.pass), keyKeeper); if(walletDB) { _walletMap[dbName] = WalletInfo(data.ownerKey, {}, walletDB); // generate default address WalletAddress address; walletDB->createAddress(address); address.m_label = "default"; walletDB->saveAddress(address); doResponse(id, CreateWallet::Response{dbName}); return; } } _apiConnection.doError(id, ApiError::InternalErrorJsonRpc, "Wallet not created."); } void onMessage(const JsonRpcId& id, const OpenWallet& data) override { LOG_DEBUG() << "OpenWallet(id = " << id << ")"; auto it = _walletMap.find(data.id); if (it == _walletMap.end()) { _walletDB = WalletDB::open(data.id + ".db", SecString(data.pass), createKeyKeeperFromDB(data.id, data.pass)); _wallet = std::make_shared<Wallet>(_walletDB); Key::IPKdf::Ptr pKey = _walletDB->get_OwnerKdf(); KeyString ks; ks.SetPassword(Blob(data.pass.data(), static_cast<uint32_t>(data.pass.size()))); ks.m_sMeta = std::to_string(0); ks.ExportP(*pKey); _walletMap[data.id].ownerKey = ks.m_sRes; } else if (auto wdb = it->second.walletDB.lock(); wdb) { _walletDB = wdb; _wallet = it->second.wallet.lock(); } else { _walletDB = WalletDB::open(data.id + ".db", SecString(data.pass), createKeyKeeper(data.pass, it->second.ownerKey)); _wallet = std::make_shared<Wallet>(_walletDB); } if(!_walletDB) { _apiConnection.doError(id, ApiError::InternalErrorJsonRpc, "Wallet not opened."); return; } _walletMap[data.id].walletDB = _walletDB; _walletMap[data.id].wallet = _wallet; LOG_INFO() << "wallet sucessfully opened..."; _wallet->ResumeAllTransactions(); auto nnet = std::make_shared<proto::FlyClient::NetworkStd>(*_wallet); nnet->m_Cfg.m_PollPeriod_ms = 0;//options.pollPeriod_ms.value; if (nnet->m_Cfg.m_PollPeriod_ms) { LOG_INFO() << "Node poll period = " << nnet->m_Cfg.m_PollPeriod_ms << " ms"; uint32_t timeout_ms = std::max(Rules::get().DA.Target_s * 1000, nnet->m_Cfg.m_PollPeriod_ms); if (timeout_ms != nnet->m_Cfg.m_PollPeriod_ms) { LOG_INFO() << "Node poll period has been automatically rounded up to block rate: " << timeout_ms << " ms"; } } uint32_t responceTime_s = Rules::get().DA.Target_s * wallet::kDefaultTxResponseTime; if (nnet->m_Cfg.m_PollPeriod_ms >= responceTime_s * 1000) { LOG_WARNING() << "The \"--node_poll_period\" parameter set to more than " << uint32_t(responceTime_s / 3600) << " hours may cause transaction problems."; } nnet->m_Cfg.m_vNodes.push_back(node_addr); nnet->Connect(); auto wnet = std::make_shared<WalletNetworkViaBbs>(*_wallet, nnet, _walletDB); _wallet->AddMessageEndpoint(wnet); _wallet->SetNodeEndpoint(nnet); // !TODO: not sure, do we need this id in the future auto session = generateUid(); doResponse(id, OpenWallet::Response{session}); } void onMessage(const JsonRpcId& id, const wallet::Ping& data) override { LOG_DEBUG() << "Ping(id = " << id << ")"; doResponse(id, wallet::Ping::Response{}); } void onMessage(const JsonRpcId& id, const Release& data) override { LOG_DEBUG() << "Release(id = " << id << ")"; doResponse(id, Release::Response{}); } static std::string generateWalletID(Key::IPKdf::Ptr ownerKdf) { Key::ID kid(Zero); kid.m_Type = ECC::Key::Type::WalletID; ECC::Point::Native pt; ECC::Hash::Value hv; kid.get_Hash(hv); ownerKdf->DerivePKeyG(pt, hv); PeerID pid; pid.Import(pt); return pid.str(); } static std::string generateUid() { std::array<uint8_t, 16> buf{}; { boost::uuids::uuid uid = boost::uuids::random_generator()(); std::copy(uid.begin(), uid.end(), buf.begin()); } return to_hex(buf.data(), buf.size()); } IPrivateKeyKeeper2::Ptr createKeyKeeper(const std::string& pass, const std::string& ownerKey) { beam::KeyString ks; ks.SetPassword(pass); ks.m_sRes = ownerKey; std::shared_ptr<ECC::HKdfPub> ownerKdf = std::make_shared<ECC::HKdfPub>(); if (ks.Import(*ownerKdf)) { return createKeyKeeper(ownerKdf); } return {}; } IPrivateKeyKeeper2::Ptr createKeyKeeperFromDB(const std::string& id, const std::string& pass) { auto walletDB = WalletDB::open(id + ".db", SecString(pass)); Key::IPKdf::Ptr pKey = walletDB->get_OwnerKdf(); return createKeyKeeper(pKey); } IPrivateKeyKeeper2::Ptr createKeyKeeper(Key::IPKdf::Ptr ownerKdf) { return std::make_shared<WasmKeyKeeperProxy>(ownerKdf, *this, _reactor); } protected: MyApiConnection _apiConnection; WebSocketServer::SendMessageFunc _sendFunc; io::Reactor::Ptr _reactor; std::queue<KeyKeeperFunc> _keeperCallbacks; IWalletDB::Ptr _walletDB; Wallet::Ptr _wallet; WalletServiceApi _api; WalletMap& _walletMap; }; }; } int main(int argc, char* argv[]) { using namespace beam; namespace po = boost::program_options; const auto path = boost::filesystem::system_complete("./logs"); auto logger = beam::Logger::create(LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, LOG_LEVEL_DEBUG, "api_", path.string()); try { struct { uint16_t port; std::string nodeURI; Nonnegative<uint32_t> pollPeriod_ms; uint32_t logCleanupPeriod; std::string allowedOrigin; } options; { po::options_description desc("Wallet API general options"); desc.add_options() (cli::HELP_FULL, "list of all options") (cli::PORT_FULL, po::value(&options.port)->default_value(8080), "port to start server on") (cli::NODE_ADDR_FULL, po::value<std::string>(&options.nodeURI), "address of node") (cli::ALLOWED_ORIGIN, po::value<std::string>(&options.allowedOrigin)->default_value(""), "allowed origin") (cli::LOG_CLEANUP_DAYS, po::value<uint32_t>(&options.logCleanupPeriod)->default_value(5), "old logfiles cleanup period(days)") (cli::NODE_POLL_PERIOD, po::value<Nonnegative<uint32_t>>(&options.pollPeriod_ms)->default_value(Nonnegative<uint32_t>(0)), "Node poll period in milliseconds. Set to 0 to keep connection. Anyway poll period would be no less than the expected rate of blocks if it is less then it will be rounded up to block rate value.") ; desc.add(createRulesOptionsDescription()); po::variables_map vm; po::store(po::command_line_parser(argc, argv) .options(desc) .style(po::command_line_style::default_style ^ po::command_line_style::allow_guessing) .run(), vm); if (vm.count(cli::HELP)) { std::cout << desc << std::endl; return 0; } { std::ifstream cfg("wallet-api.cfg"); if (cfg) { po::store(po::parse_config_file(cfg, desc), vm); } } vm.notify(); getRulesOptions(vm); Rules::get().UpdateChecksum(); LOG_INFO() << "Beam Wallet API " << PROJECT_VERSION << " (" << BRANCH_NAME << ")"; LOG_INFO() << "Rules signature: " << Rules::get().get_SignatureStr(); if (vm.count(cli::NODE_ADDR) == 0) { LOG_ERROR() << "node address should be specified"; return -1; } if (!node_addr.resolve(options.nodeURI.c_str())) { LOG_ERROR() << "unable to resolve node address: `" << options.nodeURI << "`"; return -1; } } io::Reactor::Ptr reactor = io::Reactor::create(); io::Reactor::Scope scope(*reactor); io::Reactor::GracefulIntHandler gih(*reactor); LogRotation logRotation(*reactor, LOG_ROTATION_PERIOD, options.logCleanupPeriod); LOG_INFO() << "Starting server on port " << options.port; WalletApiServer server(reactor, options.port, options.allowedOrigin); reactor->run(); LOG_INFO() << "Done"; } catch (const std::exception& e) { LOG_ERROR() << "EXCEPTION: " << e.what(); } catch (...) { LOG_ERROR() << "NON_STD EXCEPTION"; } return 0; }
<% from pwnlib.shellcraft.amd64.linux import syscall %> <%page args="fd, file, tvp"/> <%docstring> Invokes the syscall futimesat. See 'man 2 futimesat' for more information. Arguments: fd(int): fd file(char): file tvp(timeval): tvp </%docstring> ${syscall('SYS_futimesat', fd, file, tvp)}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; Copyright(c) 2011-2016 Intel Corporation All rights reserved. ; ; Redistribution and use in source and binary forms, with or without ; modification, are permitted provided that the following conditions ; are met: ; * Redistributions of source code must retain the above copyright ; notice, this list of conditions and the following disclaimer. ; * Redistributions in binary form must reproduce the above copyright ; notice, this list of conditions and the following disclaimer in ; the documentation and/or other materials provided with the ; distribution. ; * Neither the name of Intel Corporation nor the names of its ; contributors may be used to endorse or promote products derived ; from this software without specific prior written permission. ; ; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ; "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ; LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ; A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ; OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ; SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ; LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ; DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ; OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; XTS decrypt function with 128-bit AES ; expanded keys are not aligned ; plaintext and ciphertext are not aligned ; second key is stored in the stack as aligned to 16 Bytes ; first key is required only once, no need for storage of this key %include "reg_sizes.asm" default rel %define TW rsp ; store 8 tweak values %define keys rsp + 16*8 ; store 11 expanded keys %ifidn __OUTPUT_FORMAT__, win64 %define _xmm rsp + 16*19 ; store xmm6:xmm15 %endif %ifidn __OUTPUT_FORMAT__, elf64 %define _gpr rsp + 16*19 ; store rbx %define VARIABLE_OFFSET 16*8 + 16*11 + 8*1 ; VARIABLE_OFFSET has to be an odd multiple of 8 %else %define _gpr rsp + 16*29 ; store rdi, rsi, rbx %define VARIABLE_OFFSET 16*8 + 16*11 + 16*10 + 8*3 ; VARIABLE_OFFSET has to be an odd multiple of 8 %endif %define GHASH_POLY 0x87 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;void XTS_AES_128_dec_expanded_key_sse( ; UINT8 *k2, // key used for tweaking, 16*11 bytes ; UINT8 *k1, // key used for "ECB" encryption, 16*11 bytes ; UINT8 *TW_initial, // initial tweak value, 16 bytes ; UINT64 N, // sector size, in bytes ; const UINT8 *ct, // ciphertext sector input data ; UINT8 *pt); // plaintext sector output data ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ; arguments for input parameters %ifidn __OUTPUT_FORMAT__, elf64 %xdefine ptr_key2 rdi %xdefine ptr_key1 rsi %xdefine T_val rdx %xdefine N_val rcx %xdefine ptr_plaintext r8 %xdefine ptr_ciphertext r9 %else %xdefine ptr_key2 rcx %xdefine ptr_key1 rdx %xdefine T_val r8 %xdefine N_val r9 %xdefine ptr_plaintext r10; [rsp + VARIABLE_OFFSET + 8*5] %xdefine ptr_ciphertext r11; [rsp + VARIABLE_OFFSET + 8*6] %endif ; arguments for temp parameters %ifidn __OUTPUT_FORMAT__, elf64 %define tmp1 rdi %define target_ptr_val rsi %define ghash_poly_8b r10 %define ghash_poly_8b_temp r11 %else %define tmp1 rcx %define target_ptr_val rdx %define ghash_poly_8b rdi %define ghash_poly_8b_temp rsi %endif %define twtempl rax ; global temp registers used for tweak computation %define twtemph rbx ; macro to encrypt the tweak value %macro encrypt_T 8 %define %%xkey2 %1 %define %%xstate_tweak %2 %define %%xkey1 %3 %define %%xraw_key %4 %define %%xtmp %5 %define %%ptr_key2 %6 %define %%ptr_key1 %7 %define %%ptr_expanded_keys %8 movdqu %%xkey2, [%%ptr_key2] pxor %%xstate_tweak, %%xkey2 ; ARK for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*10] movdqa [%%ptr_expanded_keys+16*10], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*1] aesenc %%xstate_tweak, %%xkey2 ; round 1 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*9] movdqa [%%ptr_expanded_keys+16*9], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*2] aesenc %%xstate_tweak, %%xkey2 ; round 2 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*8] movdqa [%%ptr_expanded_keys+16*8], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*3] aesenc %%xstate_tweak, %%xkey2 ; round 3 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*7] movdqa [%%ptr_expanded_keys+16*7], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*4] aesenc %%xstate_tweak, %%xkey2 ; round 4 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*6] movdqa [%%ptr_expanded_keys+16*6], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*5] aesenc %%xstate_tweak, %%xkey2 ; round 5 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*5] movdqa [%%ptr_expanded_keys+16*5], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*6] aesenc %%xstate_tweak, %%xkey2 ; round 6 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*4] movdqa [%%ptr_expanded_keys+16*4], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*7] aesenc %%xstate_tweak, %%xkey2 ; round 7 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*3] movdqa [%%ptr_expanded_keys+16*3], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*8] aesenc %%xstate_tweak, %%xkey2 ; round 8 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*2] movdqa [%%ptr_expanded_keys+16*2], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*9] aesenc %%xstate_tweak, %%xkey2 ; round 9 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*1] movdqa [%%ptr_expanded_keys+16*1], %%xkey1 ; store round keys in stack movdqu %%xkey2, [%%ptr_key2 + 16*10] aesenclast %%xstate_tweak, %%xkey2 ; round 10 for tweak encryption movdqu %%xkey1, [%%ptr_key1 + 16*0] movdqa [%%ptr_expanded_keys+16*0], %%xkey1 ; store round keys in stack movdqa [TW], %%xstate_tweak ; Store the encrypted Tweak value %endmacro ; generate initial tweak values ; load initial plaintext values %macro initialize 16 %define %%ST1 %1 ; state 1 %define %%ST2 %2 ; state 2 %define %%ST3 %3 ; state 3 %define %%ST4 %4 ; state 4 %define %%ST5 %5 ; state 5 %define %%ST6 %6 ; state 6 %define %%ST7 %7 ; state 7 %define %%ST8 %8 ; state 8 %define %%TW1 %9 ; tweak 1 %define %%TW2 %10 ; tweak 2 %define %%TW3 %11 ; tweak 3 %define %%TW4 %12 ; tweak 4 %define %%TW5 %13 ; tweak 5 %define %%TW6 %14 ; tweak 6 %define %%TW7 %15 ; tweak 7 %define %%num_initial_blocks %16 ; generate next Tweak values movdqa %%TW1, [TW+16*0] mov twtempl, [TW+8*0] mov twtemph, [TW+8*1] movdqu %%ST1, [ptr_plaintext+16*0] %if (%%num_initial_blocks>=2) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph; movdqa %%TW2, [TW+16*1] movdqu %%ST2, [ptr_plaintext+16*1] %endif %if (%%num_initial_blocks>=3) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*4], twtempl mov [TW+8*5], twtemph; movdqa %%TW3, [TW+16*2] movdqu %%ST3, [ptr_plaintext+16*2] %endif %if (%%num_initial_blocks>=4) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*6], twtempl mov [TW+8*7], twtemph; movdqa %%TW4, [TW+16*3] movdqu %%ST4, [ptr_plaintext+16*3] %endif %if (%%num_initial_blocks>=5) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*8], twtempl mov [TW+8*9], twtemph; movdqa %%TW5, [TW+16*4] movdqu %%ST5, [ptr_plaintext+16*4] %endif %if (%%num_initial_blocks>=6) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*10], twtempl mov [TW+8*11], twtemph; movdqa %%TW6, [TW+16*5] movdqu %%ST6, [ptr_plaintext+16*5] %endif %if (%%num_initial_blocks>=7) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*12], twtempl mov [TW+8*13], twtemph; movdqa %%TW7, [TW+16*6] movdqu %%ST7, [ptr_plaintext+16*6] %endif %endmacro ; encrypt initial blocks of AES ; 1, 2, 3, 4, 5, 6 or 7 blocks are encrypted ; next 8 Tweak values are generated %macro encrypt_initial 18 %define %%ST1 %1 ; state 1 %define %%ST2 %2 ; state 2 %define %%ST3 %3 ; state 3 %define %%ST4 %4 ; state 4 %define %%ST5 %5 ; state 5 %define %%ST6 %6 ; state 6 %define %%ST7 %7 ; state 7 %define %%ST8 %8 ; state 8 %define %%TW1 %9 ; tweak 1 %define %%TW2 %10 ; tweak 2 %define %%TW3 %11 ; tweak 3 %define %%TW4 %12 ; tweak 4 %define %%TW5 %13 ; tweak 5 %define %%TW6 %14 ; tweak 6 %define %%TW7 %15 ; tweak 7 %define %%T0 %16 ; Temp register %define %%num_blocks %17 ; %%num_blocks blocks encrypted ; %%num_blocks can be 1, 2, 3, 4, 5, 6, 7 %define %%lt128 %18 ; less than 128 bytes ; xor Tweak value pxor %%ST1, %%TW1 %if (%%num_blocks>=2) pxor %%ST2, %%TW2 %endif %if (%%num_blocks>=3) pxor %%ST3, %%TW3 %endif %if (%%num_blocks>=4) pxor %%ST4, %%TW4 %endif %if (%%num_blocks>=5) pxor %%ST5, %%TW5 %endif %if (%%num_blocks>=6) pxor %%ST6, %%TW6 %endif %if (%%num_blocks>=7) pxor %%ST7, %%TW7 %endif ; ARK movdqa %%T0, [keys] pxor %%ST1, %%T0 %if (%%num_blocks>=2) pxor %%ST2, %%T0 %endif %if (%%num_blocks>=3) pxor %%ST3, %%T0 %endif %if (%%num_blocks>=4) pxor %%ST4, %%T0 %endif %if (%%num_blocks>=5) pxor %%ST5, %%T0 %endif %if (%%num_blocks>=6) pxor %%ST6, %%T0 %endif %if (%%num_blocks>=7) pxor %%ST7, %%T0 %endif %if (0 == %%lt128) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph %endif ; round 1 movdqa %%T0, [keys + 16*1] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*0], twtempl ; next Tweak1 generated mov [TW + 8*1], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp %endif ; round 2 movdqa %%T0, [keys + 16*2] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*2], twtempl ; next Tweak2 generated %endif ; round 3 movdqa %%T0, [keys + 16*3] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) mov [TW + 8*3], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b %endif ; round 4 movdqa %%T0, [keys + 16*4] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) xor twtempl, ghash_poly_8b_temp mov [TW + 8*4], twtempl ; next Tweak3 generated mov [TW + 8*5], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 %endif ; round 5 movdqa %%T0, [keys + 16*5] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*6], twtempl ; next Tweak4 generated mov [TW + 8*7], twtemph %endif ; round 6 movdqa %%T0, [keys + 16*6] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*8], twtempl ; next Tweak5 generated mov [TW + 8*9], twtemph %endif ; round 7 movdqa %%T0, [keys + 16*7] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*10], twtempl ; next Tweak6 generated mov [TW + 8*11], twtemph %endif ; round 8 movdqa %%T0, [keys + 16*8] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*12], twtempl ; next Tweak7 generated mov [TW + 8*13], twtemph %endif ; round 9 movdqa %%T0, [keys + 16*9] aesdec %%ST1, %%T0 %if (%%num_blocks>=2) aesdec %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdec %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdec %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdec %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdec %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdec %%ST7, %%T0 %endif %if (0 == %%lt128) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*14], twtempl ; next Tweak8 generated mov [TW + 8*15], twtemph %endif ; round 10 movdqa %%T0, [keys + 16*10] aesdeclast %%ST1, %%T0 %if (%%num_blocks>=2) aesdeclast %%ST2, %%T0 %endif %if (%%num_blocks>=3) aesdeclast %%ST3, %%T0 %endif %if (%%num_blocks>=4) aesdeclast %%ST4, %%T0 %endif %if (%%num_blocks>=5) aesdeclast %%ST5, %%T0 %endif %if (%%num_blocks>=6) aesdeclast %%ST6, %%T0 %endif %if (%%num_blocks>=7) aesdeclast %%ST7, %%T0 %endif ; xor Tweak values pxor %%ST1, %%TW1 %if (%%num_blocks>=2) pxor %%ST2, %%TW2 %endif %if (%%num_blocks>=3) pxor %%ST3, %%TW3 %endif %if (%%num_blocks>=4) pxor %%ST4, %%TW4 %endif %if (%%num_blocks>=5) pxor %%ST5, %%TW5 %endif %if (%%num_blocks>=6) pxor %%ST6, %%TW6 %endif %if (%%num_blocks>=7) pxor %%ST7, %%TW7 %endif %if (0 == %%lt128) ; load next Tweak values movdqa %%TW1, [TW + 16*0] movdqa %%TW2, [TW + 16*1] movdqa %%TW3, [TW + 16*2] movdqa %%TW4, [TW + 16*3] movdqa %%TW5, [TW + 16*4] movdqa %%TW6, [TW + 16*5] movdqa %%TW7, [TW + 16*6] %endif %endmacro ; Encrypt 8 blocks in parallel ; generate next 8 tweak values %macro encrypt_by_eight 18 %define %%ST1 %1 ; state 1 %define %%ST2 %2 ; state 2 %define %%ST3 %3 ; state 3 %define %%ST4 %4 ; state 4 %define %%ST5 %5 ; state 5 %define %%ST6 %6 ; state 6 %define %%ST7 %7 ; state 7 %define %%ST8 %8 ; state 8 %define %%TW1 %9 ; tweak 1 %define %%TW2 %10 ; tweak 2 %define %%TW3 %11 ; tweak 3 %define %%TW4 %12 ; tweak 4 %define %%TW5 %13 ; tweak 5 %define %%TW6 %14 ; tweak 6 %define %%TW7 %15 ; tweak 7 %define %%TW8 %16 ; tweak 8 %define %%T0 %17 ; Temp register %define %%last_eight %18 ; xor Tweak values pxor %%ST1, %%TW1 pxor %%ST2, %%TW2 pxor %%ST3, %%TW3 pxor %%ST4, %%TW4 pxor %%ST5, %%TW5 pxor %%ST6, %%TW6 pxor %%ST7, %%TW7 pxor %%ST8, %%TW8 ; ARK movdqa %%T0, [keys] pxor %%ST1, %%T0 pxor %%ST2, %%T0 pxor %%ST3, %%T0 pxor %%ST4, %%T0 pxor %%ST5, %%T0 pxor %%ST6, %%T0 pxor %%ST7, %%T0 pxor %%ST8, %%T0 %if (0 == %%last_eight) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b %endif ; round 1 movdqa %%T0, [keys + 16*1] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) xor twtempl, ghash_poly_8b_temp mov [TW + 8*0], twtempl mov [TW + 8*1], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp %endif ; round 2 movdqa %%T0, [keys + 16*2] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp %endif ; round 3 movdqa %%T0, [keys + 16*3] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) mov [TW + 8*2], twtempl mov [TW + 8*3], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 %endif ; round 4 movdqa %%T0, [keys + 16*4] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*4], twtempl %endif ; round 5 movdqa %%T0, [keys + 16*5] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) mov [TW + 8*5], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph %endif ; round 6 movdqa %%T0, [keys + 16*6] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*6], twtempl mov [TW + 8*7], twtemph %endif ; round 7 movdqa %%T0, [keys + 16*7] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b %endif ; round 8 movdqa %%T0, [keys + 16*8] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) xor twtempl, ghash_poly_8b_temp mov [TW + 8*8], twtempl mov [TW + 8*9], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp %endif ; round 9 movdqa %%T0, [keys + 16*9] aesdec %%ST1, %%T0 aesdec %%ST2, %%T0 aesdec %%ST3, %%T0 aesdec %%ST4, %%T0 aesdec %%ST5, %%T0 aesdec %%ST6, %%T0 aesdec %%ST7, %%T0 aesdec %%ST8, %%T0 %if (0 == %%last_eight) shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp %endif %if (0 == %%last_eight) mov [TW + 8*10], twtempl mov [TW + 8*11], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 %endif %if (0 == %%last_eight) adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW + 8*12], twtempl %endif %if (0 == %%last_eight) mov [TW + 8*13], twtemph xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph %endif %if (0 == %%last_eight) cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp ; mov [TW + 8*14], twtempl ; mov [TW + 8*15], twtemph %endif ; round 10 movdqa %%T0, [keys + 16*10] aesdeclast %%ST1, %%T0 aesdeclast %%ST2, %%T0 aesdeclast %%ST3, %%T0 aesdeclast %%ST4, %%T0 aesdeclast %%ST5, %%T0 aesdeclast %%ST6, %%T0 aesdeclast %%ST7, %%T0 aesdeclast %%ST8, %%T0 ; xor Tweak values pxor %%ST1, %%TW1 pxor %%ST2, %%TW2 pxor %%ST3, %%TW3 pxor %%ST4, %%TW4 pxor %%ST5, %%TW5 pxor %%ST6, %%TW6 pxor %%ST7, %%TW7 pxor %%ST8, %%TW8 mov [TW + 8*14], twtempl mov [TW + 8*15], twtemph ; load next Tweak values movdqa %%TW1, [TW + 16*0] movdqa %%TW2, [TW + 16*1] movdqa %%TW3, [TW + 16*2] movdqa %%TW4, [TW + 16*3] movdqa %%TW5, [TW + 16*4] movdqa %%TW6, [TW + 16*5] movdqa %%TW7, [TW + 16*6] %endmacro section .text mk_global XTS_AES_128_dec_expanded_key_sse, function XTS_AES_128_dec_expanded_key_sse: sub rsp, VARIABLE_OFFSET mov [_gpr + 8*0], rbx %ifidn __OUTPUT_FORMAT__, win64 mov [_gpr + 8*1], rdi mov [_gpr + 8*2], rsi movdqa [_xmm + 16*0], xmm6 movdqa [_xmm + 16*1], xmm7 movdqa [_xmm + 16*2], xmm8 movdqa [_xmm + 16*3], xmm9 movdqa [_xmm + 16*4], xmm10 movdqa [_xmm + 16*5], xmm11 movdqa [_xmm + 16*6], xmm12 movdqa [_xmm + 16*7], xmm13 movdqa [_xmm + 16*8], xmm14 movdqa [_xmm + 16*9], xmm15 %endif mov ghash_poly_8b, GHASH_POLY ; load 0x87 to ghash_poly_8b movdqu xmm1, [T_val] ; read initial Tweak value pxor xmm4, xmm4 ; for key expansion encrypt_T xmm0, xmm1, xmm2, xmm3, xmm4, ptr_key2, ptr_key1, keys %ifidn __OUTPUT_FORMAT__, win64 mov ptr_plaintext, [rsp + VARIABLE_OFFSET + 8*5] ; plaintext pointer mov ptr_ciphertext, [rsp + VARIABLE_OFFSET + 8*6] ; ciphertext pointer %endif mov target_ptr_val, N_val and target_ptr_val, -16 ; target_ptr_val = target_ptr_val - (target_ptr_val mod 16) sub target_ptr_val, 128 ; adjust target_ptr_val because last 4 blocks will not be stitched with Tweak calculations jl _less_than_128_bytes add target_ptr_val, ptr_ciphertext mov tmp1, N_val and tmp1, (7 << 4) jz _initial_num_blocks_is_0 cmp tmp1, (4 << 4) je _initial_num_blocks_is_4 cmp tmp1, (6 << 4) je _initial_num_blocks_is_6 cmp tmp1, (5 << 4) je _initial_num_blocks_is_5 cmp tmp1, (3 << 4) je _initial_num_blocks_is_3 cmp tmp1, (2 << 4) je _initial_num_blocks_is_2 cmp tmp1, (1 << 4) je _initial_num_blocks_is_1 _initial_num_blocks_is_7: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 7 add ptr_plaintext, 16*7 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 7, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 movdqu [ptr_ciphertext+16*6], xmm7 add ptr_ciphertext, 16*7 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_6: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 6 add ptr_plaintext, 16*6 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 6, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 add ptr_ciphertext, 16*6 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_5: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 5 add ptr_plaintext, 16*5 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 5, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 add ptr_ciphertext, 16*5 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_4: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 4 add ptr_plaintext, 16*4 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 4, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 add ptr_ciphertext, 16*4 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_3: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 3 add ptr_plaintext, 16*3 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 3, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 add ptr_ciphertext, 16*3 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_2: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 2 add ptr_plaintext, 16*2 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 2, 0 ; store ciphertext movdqu [ptr_ciphertext], xmm1 movdqu [ptr_ciphertext+16], xmm2 add ptr_ciphertext, 16*2 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_1: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 1 add ptr_plaintext, 16*1 encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 1, 0 ; store ciphertext movdqu [ptr_ciphertext], xmm1 add ptr_ciphertext, 16 cmp ptr_ciphertext, target_ptr_val je _last_eight jmp _main_loop _initial_num_blocks_is_0: mov twtempl, [TW+8*0] mov twtemph, [TW+8*1] movdqa xmm9, [TW+16*0] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa xmm10, [TW+16*1] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*4], twtempl mov [TW+8*5], twtemph movdqa xmm11, [TW+16*2] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*6], twtempl mov [TW+8*7], twtemph movdqa xmm12, [TW+16*3] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*8], twtempl mov [TW+8*9], twtemph movdqa xmm13, [TW+16*4] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*10], twtempl mov [TW+8*11], twtemph movdqa xmm14, [TW+16*5] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*12], twtempl mov [TW+8*13], twtemph movdqa xmm15, [TW+16*6] xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*14], twtempl mov [TW+8*15], twtemph ;movdqa xmm16, [TW+16*7] cmp ptr_ciphertext, target_ptr_val je _last_eight _main_loop: ; load plaintext movdqu xmm1, [ptr_plaintext+16*0] movdqu xmm2, [ptr_plaintext+16*1] movdqu xmm3, [ptr_plaintext+16*2] movdqu xmm4, [ptr_plaintext+16*3] movdqu xmm5, [ptr_plaintext+16*4] movdqu xmm6, [ptr_plaintext+16*5] movdqu xmm7, [ptr_plaintext+16*6] movdqu xmm8, [ptr_plaintext+16*7] add ptr_plaintext, 128 encrypt_by_eight xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, [TW+16*7], xmm0, 0 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 movdqu [ptr_ciphertext+16*6], xmm7 movdqu [ptr_ciphertext+16*7], xmm8 add ptr_ciphertext, 128 cmp ptr_ciphertext, target_ptr_val jne _main_loop _last_eight: and N_val, 15 ; N_val = N_val mod 16 je _done_final ; generate next Tweak value xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp movdqa xmm1, [TW + 16*7] movdqa [TW + 16*0], xmm1 ; swap tweak values for cipher stealing for decrypt mov [TW + 16*7], twtempl mov [TW + 16*7+8], twtemph ; load plaintext movdqu xmm1, [ptr_plaintext+16*0] movdqu xmm2, [ptr_plaintext+16*1] movdqu xmm3, [ptr_plaintext+16*2] movdqu xmm4, [ptr_plaintext+16*3] movdqu xmm5, [ptr_plaintext+16*4] movdqu xmm6, [ptr_plaintext+16*5] movdqu xmm7, [ptr_plaintext+16*6] movdqu xmm8, [ptr_plaintext+16*7] encrypt_by_eight xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, [TW+16*7], xmm0, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 movdqu [ptr_ciphertext+16*6], xmm7 jmp _steal_cipher _done_final: ; load plaintext movdqu xmm1, [ptr_plaintext+16*0] movdqu xmm2, [ptr_plaintext+16*1] movdqu xmm3, [ptr_plaintext+16*2] movdqu xmm4, [ptr_plaintext+16*3] movdqu xmm5, [ptr_plaintext+16*4] movdqu xmm6, [ptr_plaintext+16*5] movdqu xmm7, [ptr_plaintext+16*6] movdqu xmm8, [ptr_plaintext+16*7] encrypt_by_eight xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, [TW+16*7], xmm0, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 movdqu [ptr_ciphertext+16*6], xmm7 jmp _done _steal_cipher: ; start cipher stealing movdqa xmm2, xmm8 ; shift xmm8 to the left by 16-N_val bytes lea twtempl, [pshufb_shf_table] movdqu xmm0, [twtempl+N_val] pshufb xmm8, xmm0 movdqu xmm3, [ptr_plaintext + 112 + N_val] ; state register is temporarily xmm3 to eliminate a move movdqu [ptr_ciphertext + 112 + N_val], xmm8 ; shift xmm3 to the right by 16-N_val bytes lea twtempl, [pshufb_shf_table +16] sub twtempl, N_val movdqu xmm0, [twtempl] pxor xmm0, [mask1] pshufb xmm3, xmm0 pblendvb xmm3, xmm2 ;xmm0 is implicit ; xor Tweak value movdqa xmm8, [TW] pxor xmm8, xmm3 ; state register is xmm8, instead of a move from xmm3 to xmm8, destination register of pxor instruction is swapped ;encrypt last block with cipher stealing pxor xmm8, [keys] ; ARK aesdec xmm8, [keys + 16*1] ; round 1 aesdec xmm8, [keys + 16*2] ; round 2 aesdec xmm8, [keys + 16*3] ; round 3 aesdec xmm8, [keys + 16*4] ; round 4 aesdec xmm8, [keys + 16*5] ; round 5 aesdec xmm8, [keys + 16*6] ; round 6 aesdec xmm8, [keys + 16*7] ; round 7 aesdec xmm8, [keys + 16*8] ; round 8 aesdec xmm8, [keys + 16*9] ; round 9 aesdeclast xmm8, [keys + 16*10] ; round 10 ; xor Tweak value pxor xmm8, [TW] _done: ; store last ciphertext value movdqu [ptr_ciphertext+16*7], xmm8 _ret_: mov rbx, [_gpr + 8*0] %ifidn __OUTPUT_FORMAT__, win64 mov rdi, [_gpr + 8*1] mov rsi, [_gpr + 8*2] movdqa xmm6, [_xmm + 16*0] movdqa xmm7, [_xmm + 16*1] movdqa xmm8, [_xmm + 16*2] movdqa xmm9, [_xmm + 16*3] movdqa xmm10, [_xmm + 16*4] movdqa xmm11, [_xmm + 16*5] movdqa xmm12, [_xmm + 16*6] movdqa xmm13, [_xmm + 16*7] movdqa xmm14, [_xmm + 16*8] movdqa xmm15, [_xmm + 16*9] %endif add rsp, VARIABLE_OFFSET ret _less_than_128_bytes: cmp N_val, 16 jb _ret_ mov tmp1, N_val and tmp1, (7 << 4) cmp tmp1, (6 << 4) je _num_blocks_is_6 cmp tmp1, (5 << 4) je _num_blocks_is_5 cmp tmp1, (4 << 4) je _num_blocks_is_4 cmp tmp1, (3 << 4) je _num_blocks_is_3 cmp tmp1, (2 << 4) je _num_blocks_is_2 cmp tmp1, (1 << 4) je _num_blocks_is_1 _num_blocks_is_7: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 7 sub ptr_plaintext, 16*1 and N_val, 15 ; N_val = N_val mod 16 je _done_7 _steal_cipher_7: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm15 movdqa xmm15, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 7, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 sub ptr_ciphertext, 16*1 movdqa xmm8, xmm7 jmp _steal_cipher _done_7: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 7, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 movdqu [ptr_ciphertext+16*5], xmm6 sub ptr_ciphertext, 16*1 movdqa xmm8, xmm7 jmp _done _num_blocks_is_6: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 6 sub ptr_plaintext, 16*2 and N_val, 15 ; N_val = N_val mod 16 je _done_6 _steal_cipher_6: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm14 movdqa xmm14, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 6, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 sub ptr_ciphertext, 16*2 movdqa xmm8, xmm6 jmp _steal_cipher _done_6: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 6, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 movdqu [ptr_ciphertext+16*4], xmm5 sub ptr_ciphertext, 16*2 movdqa xmm8, xmm6 jmp _done _num_blocks_is_5: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 5 sub ptr_plaintext, 16*3 and N_val, 15 ; N_val = N_val mod 16 je _done_5 _steal_cipher_5: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm13 movdqa xmm13, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 5, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 sub ptr_ciphertext, 16*3 movdqa xmm8, xmm5 jmp _steal_cipher _done_5: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 5, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 movdqu [ptr_ciphertext+16*3], xmm4 sub ptr_ciphertext, 16*3 movdqa xmm8, xmm5 jmp _done _num_blocks_is_4: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 4 sub ptr_plaintext, 16*4 and N_val, 15 ; N_val = N_val mod 16 je _done_4 _steal_cipher_4: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm12 movdqa xmm12, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 4, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 sub ptr_ciphertext, 16*4 movdqa xmm8, xmm4 jmp _steal_cipher _done_4: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 4, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 movdqu [ptr_ciphertext+16*2], xmm3 sub ptr_ciphertext, 16*4 movdqa xmm8, xmm4 jmp _done _num_blocks_is_3: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 3 sub ptr_plaintext, 16*5 and N_val, 15 ; N_val = N_val mod 16 je _done_3 _steal_cipher_3: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm11 movdqa xmm11, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 3, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 sub ptr_ciphertext, 16*5 movdqa xmm8, xmm3 jmp _steal_cipher _done_3: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 3, 1 ; store ciphertext movdqu [ptr_ciphertext+16*0], xmm1 movdqu [ptr_ciphertext+16*1], xmm2 sub ptr_ciphertext, 16*5 movdqa xmm8, xmm3 jmp _done _num_blocks_is_2: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 2 sub ptr_plaintext, 16*6 and N_val, 15 ; N_val = N_val mod 16 je _done_2 _steal_cipher_2: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm10 movdqa xmm10, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 2, 1 ; store ciphertext movdqu [ptr_ciphertext], xmm1 sub ptr_ciphertext, 16*6 movdqa xmm8, xmm2 jmp _steal_cipher _done_2: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 2, 1 ; store ciphertext movdqu [ptr_ciphertext], xmm1 sub ptr_ciphertext, 16*6 movdqa xmm8, xmm2 jmp _done _num_blocks_is_1: initialize xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, 1 sub ptr_plaintext, 16*7 and N_val, 15 ; N_val = N_val mod 16 je _done_1 _steal_cipher_1: xor ghash_poly_8b_temp, ghash_poly_8b_temp shl twtempl, 1 adc twtemph, twtemph cmovc ghash_poly_8b_temp, ghash_poly_8b xor twtempl, ghash_poly_8b_temp mov [TW+8*2], twtempl mov [TW+8*3], twtemph movdqa [TW + 16*0] , xmm9 movdqa xmm9, [TW+16*1] encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 1, 1 ; store ciphertext sub ptr_ciphertext, 16*7 movdqa xmm8, xmm1 jmp _steal_cipher _done_1: encrypt_initial xmm1, xmm2, xmm3, xmm4, xmm5, xmm6, xmm7, xmm8, xmm9, xmm10, xmm11, xmm12, xmm13, xmm14, xmm15, xmm0, 1, 1 ; store ciphertext sub ptr_ciphertext, 16*7 movdqa xmm8, xmm1 jmp _done section .data align 16 pshufb_shf_table: ; use these values for shift constants for the pshufb instruction ; different alignments result in values as shown: ; dq 0x8887868584838281, 0x008f8e8d8c8b8a89 ; shl 15 (16-1) / shr1 ; dq 0x8988878685848382, 0x01008f8e8d8c8b8a ; shl 14 (16-3) / shr2 ; dq 0x8a89888786858483, 0x0201008f8e8d8c8b ; shl 13 (16-4) / shr3 ; dq 0x8b8a898887868584, 0x030201008f8e8d8c ; shl 12 (16-4) / shr4 ; dq 0x8c8b8a8988878685, 0x04030201008f8e8d ; shl 11 (16-5) / shr5 ; dq 0x8d8c8b8a89888786, 0x0504030201008f8e ; shl 10 (16-6) / shr6 ; dq 0x8e8d8c8b8a898887, 0x060504030201008f ; shl 9 (16-7) / shr7 ; dq 0x8f8e8d8c8b8a8988, 0x0706050403020100 ; shl 8 (16-8) / shr8 ; dq 0x008f8e8d8c8b8a89, 0x0807060504030201 ; shl 7 (16-9) / shr9 ; dq 0x01008f8e8d8c8b8a, 0x0908070605040302 ; shl 6 (16-10) / shr10 ; dq 0x0201008f8e8d8c8b, 0x0a09080706050403 ; shl 5 (16-11) / shr11 ; dq 0x030201008f8e8d8c, 0x0b0a090807060504 ; shl 4 (16-12) / shr12 ; dq 0x04030201008f8e8d, 0x0c0b0a0908070605 ; shl 3 (16-13) / shr13 ; dq 0x0504030201008f8e, 0x0d0c0b0a09080706 ; shl 2 (16-14) / shr14 ; dq 0x060504030201008f, 0x0e0d0c0b0a090807 ; shl 1 (16-15) / shr15 dq 0x8786858483828100, 0x8f8e8d8c8b8a8988 dq 0x0706050403020100, 0x000e0d0c0b0a0908 mask1: dq 0x8080808080808080, 0x8080808080808080
Name: zel_sub0.asm Type: file Size: 21959 Last-Modified: '2016-05-13T04:23:03Z' SHA-1: 88302E91DCF659A4785D0E7B8B19920E5A0E6245 Description: null
; A065113: Sum of the squares of the n-th and the (n+1)st triangular numbers (A000217) is a perfect square. ; 6,40,238,1392,8118,47320,275806,1607520,9369318,54608392,318281038,1855077840,10812186006,63018038200,367296043198,2140758220992,12477253282758,72722761475560,423859315570606,2470433131948080,14398739476117878,83922003724759192,489133282872437278,2850877693509864480,16616132878186749606,96845919575610633160,564459384575477049358,3289910387877251662992,19175002942688032928598,111760107268250945908600,651385640666817642523006,3796553736732654909229440,22127936779729111812853638,128971066941642015967892392,751698464870122983994500718,4381219722279095887999111920,25535619868804452344000170806,148832499490547618176001912920,867459377074481256712011306718,5055923762956339922096065927392,29468083200663558275864384257638,171752575441025009733090239618440,1001047369445486500122677053453006,5834531641231893991002972081099600,34006142477945877445895155433144598,198202323226443370684367960517767992 mov $1,7 mov $2,5 lpb $0 sub $0,1 add $1,$2 add $2,$1 add $2,$1 add $1,$2 lpe mov $0,$1 sub $0,1
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="which, who, prio"/> <%docstring> Invokes the syscall setpriority. See 'man 2 setpriority' for more information. Arguments: which(priority_which_t): which who(id_t): who prio(int): prio </%docstring> ${syscall('SYS_setpriority', which, who, prio)}
// Copyright (c) 2018 Microsoft Corporation // Licensed under the MIT license. // Author: Paul Koch <code@koch.ninja> #include "precompiled_header_cpp.hpp" // TODO: use noexcept throughout our codebase (exception extern "C" functions) ! The compiler can optimize functions better if it knows there are no exceptions // TODO: review all the C++ library calls, including things like std::abs and verify that none of them throw exceptions, otherwise use the C versions that provide this guarantee #include <stddef.h> // size_t, ptrdiff_t #include <limits> // std::numeric_limits #include "ebm_native.h" #include "logging.h" #include "zones.h" #include "ebm_internal.hpp" namespace DEFINED_ZONE_NAME { #ifndef DEFINED_ZONE_NAME #error DEFINED_ZONE_NAME must be defined #endif // DEFINED_ZONE_NAME EBM_NATIVE_IMPORT_EXPORT_BODY ErrorEbmType EBM_NATIVE_CALLING_CONVENTION Softmax( IntEbmType countTargetClasses, IntEbmType countSamples, const FloatEbmType * logits, FloatEbmType * probabilitiesOut ) { UNUSED(countTargetClasses); UNUSED(countSamples); UNUSED(logits); UNUSED(probabilitiesOut); return Error_UnexpectedInternal; //if(2 != countTargetClasses) { // // TODO: handle multiclass // exit(1); //}; //UNUSED(countTargetClasses); // TODO: use this //for(size_t i = 0; i < static_cast<size_t>(countSamples); ++i) { // // NOTE: we use the non-approximate std::exp because we want our predictions to match what other softmax functions // // will generate instead of the approximation, and ordering is more sensitive to noise than boosting // const FloatEbmType odds = std::exp(logits[i]); // probabilitiesOut[i] = odds / (FloatEbmType { 1 } + odds); //} //return Error_None; } // Plan: // - when making predictions, in the great majority of cases, we should serially determine the logits of each // sample per feature and then later add those logits. It's tempting to want to process more than one feature // at a time, but that's a red-hearing: // - data typically gets passed to us as C ordered data, so feature0 and feature1 are in adjacent memory // cells, and sample0 and sample1 are distant. It's less costly to read the data per feature for our pure input // data. It wouldn't do us much good though if we striped just two features at a time, so we'd want to // process all N features in order to take advantage of this property. But if you do that, then we'd need // to do binary searches on a single sample for a single feature, then fetch into cache the next feature's // cut "definition". The cost of constantly bringing into L1 cache the cut points and logits for each feature // would entail more memory movement than either processing the matrix out of order or transposing it beforehand // - it's tempting to then consider striping just 2 features or some limited subset. We get limited speed benefits // when processing two features at a time since at best it halves the time to access the matrix, but we still // then need to keep two cut point arrays that we do unpredictable branches on and it potentially pushes some // of our cut point and logit arrays out from L1 cache into L2 or beyond // - we get benefits by having special case algorithms based on the number of cut points (see below where we // do linear searches for small numbers of cut points, and pad cut point arrays for slightly larger numbers of // cut points). And it's hard to see how we could combine these together and say have a special loop to handle // when one feature has 3 cut points, and the other has 50 cut points // - one of the benefits of doing 2 features at once would be that we could add the logits together and write // the sum to memory instead of writing both logits and later reading those again and summing them and writing // them back to memory, but since we'd be doing this with correcly ordered memory, we'd be able to stream // the reads and the writes such that they'd take approx 1 clock cycle each, so in reality we don't gain much // from combining the logits at binary search time // - in theory we might gain something if we had two single cut features because we could load the 2 values we're // cutting into 2 registers, then have the cut points in 2 persistent registers, and have 4 registers for the // logit results. We can overwrite one of the two registers loaded with the sum of the resulting logits. // That's a total of 8 registers. For 2 cuts, we'd need 2 for loading, 4 for cuts, 6 for logits, so 12 registers // Which is also doable. Beyond that, we'd need to use or access memory when combining processing for 2 features // and I think it would be better to pay the streaming to memory cost than to fetch somewhat unpredictably // the cut points or logits // - even if we did write special case code for handling two binary features, it won't help us if the matrix the // user passes us doesn't put the binary features adjacent to eachother. We can't re-arrange the columsn for // less than the cost of partial transposes, so we'd rather just go with partial transposes // - doing a partial striped transpose is 32% faster in my tests than reading 2 columns at once, so we'd be // better off transposing the two columns than process them. This is because we are limited to reading just // two values efficiently at a time, rather than reading a full stripe efficiently. // - we can get data from the user as fortran ordered. If it comes to us fortran ordered // then great, because our accessing that data per feature is very efficient (approx 1 clock cycle per read) // - we can get data from the user as C ordered (this is more common). We could read the matrix in poor memory // order, but then we're still loading in a complete cache line at a time. It makes more sense to read in data // in a stripe and transpose it that way. I did some perfs, and reading stripes of 64 doubles was fastest // We pay the cost of having 64 write streams, but our reads are very fast. That's the break even point though // - transposing the complete matrix would double our memory requirements. Since transposing is fastest with 64 // doubles though, we can extract and transpose our original C ordered data in 64 feature groupings // - we can use SIMD easily enough by loading the next 2/4/8 doubles at a time and re-using the same cut definition // within a single processor // - we can use threading efficiently in one of two ways. We can subdivide the samples up by the number of CPUs // and have each CPU process those ranges. This allows all the CPUs to utilize the same cut point definitions // but they have smaller batches. Alternatively, we can give each CPU one feature and have it load the cut // point and logit definitions into it's L1 cache which isn't likely to be shared. If some of the cut points // or logits need to be in L2 though, there might be bad contention. // - hyper-threads would probably benefit from having the same cut points and logits since both hyper-threads share // the L1 cahce, so the "best" solution is probably use thread afinity to keep CPUs working on the same feature // and dividing up the samples between the hyper-threads, but then benefit from larger batch sizes by putting // different features on different CPUs // - the exact threading solution will probably depend on exact numbers of samples and threads and machine // architecture // - whether dividing the work by samples or features or a mix, if we make multiple calls into our discritize // function, we would want to preserve our threads since they are costly to make, so we'd want to have a // thread allocation object that we'd free after discretization // - for fortran ordered arrays, the user might as well pass us the entire array and we'll process it directly // - for C ordered data, either the 64 stride transpose happens in our higher level caller, or they just pass // us the C ordered data, and we do the partial transposes inside C++ from the badly ordered original data // - in the entire dataset gets passed to us, then we don't need a thread allocation object since we just do it once // - if the original array is in pandas, it seems to be stored internally as a numpy array if the datatypes are all // the same, so we can pass that direclty into our function // - if the original array is in pandas, and consists of strings or integers or anything heterogenious, then // the data appears to be fortran ordered. In that case we'd like to pass the data in that bare format // - but we're not sure that pandas stores these as 2-D matricies or multiple 1-D arrays. If the ladder, then // we either need to process it one array at a time, or copy the data together. // - handling strings can either be done with python vectorized functions or in cython (try pure python first) // - after our per-feature logit arrays have been written, we can load in several at a time and add them together // and write out the result, and we can parallelize that operation until all the logits have been added // - SIMD reads and writes are better on certain boundaries. We don't control the data passed to us from the user // so we might want to read the first few instances with a special binary search function and then start // on the SIMD on a memory aligned boundary, then also use the special binary search function for the last few // - one complication is that for pairs we need to have both feature in memory to evaluate. If the pairs are // not in the same stripe we need to preserve them until they are. In most cases we can probably just hold the // features we need or organize which stripes we load at which times, but in the worst case we may want // to re-discretize some features, or in the worst case discretize all features (preserving in a compressed // format?). This really needs to be threshed out. // // - Table of matrix access speeds (for summing cells in a matrix): // bad_order = 7.43432 // stride_1 = 7.27575 // stride_2 = 4.08857 // stride_16384 = 0.431882 // transpose_1 = 10.4326 // transpose_2 = 6.49787 // transpose_4 = 4.54615 // transpose_8 = 3.42918 // transpose_16 = 3.04755 // transpose_32 = 2.80757 // transpose_64 = 2.75464 // transpose_128 = 2.79845 // transpose_256 = 2.8748 // transpose_512 = 2.96725 // transpose_1024 = 3.17072 // transpose_2048 = 6.04042 // transpose_4096 = 6.1348 // transpose_8192 = 6.26907 // transpose_16384 = 7.73406 EBM_NATIVE_IMPORT_EXPORT_BODY IntEbmType EBM_NATIVE_CALLING_CONVENTION DiscretizeOne( const FloatEbmType featureValue, IntEbmType countCuts, const FloatEbmType * cutsLowerBoundInclusive ) { // unlike all of our other public interfaces we don't check our inputs for validity. The caller is expected // to get these right otherwise there will be a segfault. We do this because we want lightening fast prediction // speed. We can still use EBM_ASSERT though to catch input errors on debug builds, so do that. EBM_ASSERT(nullptr != cutsLowerBoundInclusive); EBM_ASSERT(IntEbmType { 0 } <= countCuts); // IntEbmType::max should be the maximum number of bins that we allow. This prevents our caller from accidentally // overflowing when using either the count (eg: 255) or the index (eg: 0-254). The 0th bin is the special missing // bin, so we have max-1 normal bins. We have 1 less cuts than we have bins (1 cut means 2 bins), so we can // have a maximum of max - 2 cuts. EBM_ASSERT(countCuts <= std::numeric_limits<IntEbmType>::max() - IntEbmType { 2 }); // cutsLowerBoundInclusive needs to hold all the cuts, so we should be able to at least convert countCuts to size_t EBM_ASSERT(!IsConvertError<size_t>(countCuts)); // cutsLowerBoundInclusive needs to hold all the cuts, so all the bytes need to be addressable EBM_ASSERT(!IsMultiplyError(sizeof(*cutsLowerBoundInclusive), static_cast<size_t>(countCuts))); // extra restrictions we take on from our binary search code // we use ptrdiff_t as our indexes in the binary search code since it's slightly faster EBM_ASSERT(!IsConvertError<ptrdiff_t>(countCuts)); // we add 1 to static_cast<size_t>(countCuts) as our missing value, so this addition must succeed EBM_ASSERT(static_cast<size_t>(countCuts) < std::numeric_limits<size_t>::max()); // the low value can increase until it's equal to cCuts, so cCuts must be expressable as a ptrdiff_t // we need to keep low as a ptrdiff_t since we compare it right after with high, which can be -1 EBM_ASSERT(static_cast<size_t>(countCuts) <= size_t { std::numeric_limits<ptrdiff_t>::max() }); // our first operation towards getting the mid-point is to add the size_t low and size_t high, and that can't // overflow, so check that the maximum high added to the maximum low (which is the high) don't exceed that value EBM_ASSERT(static_cast<size_t>(countCuts) <= std::numeric_limits<size_t>::max() / size_t { 2 } + size_t { 1 }); if(PREDICTABLE(std::isnan(featureValue))) { return IntEbmType { 0 }; } if(UNLIKELY(countCuts <= IntEbmType { 0 })) { return IntEbmType { 1 }; } size_t middle; const ptrdiff_t highStart = static_cast<ptrdiff_t>(countCuts) - ptrdiff_t { 1 }; ptrdiff_t high = highStart; ptrdiff_t low = ptrdiff_t { 0 }; FloatEbmType midVal; do { EBM_ASSERT(ptrdiff_t { 0 } <= low && static_cast<size_t>(low) < static_cast<size_t>(countCuts)); EBM_ASSERT(ptrdiff_t { 0 } <= high && static_cast<size_t>(high) < static_cast<size_t>(countCuts)); EBM_ASSERT(low <= high); // low is equal or lower than high, so summing them can't exceed 2 * high, and after division it // can't be higher than high, so middle can't overflow ptrdiff_t after the division since high // is already a ptrdiff_t. Generally the maximum positive value of a ptrdiff_t can be doubled // when converted to a size_t, although that isn't guaranteed. A more correct statement is that // the following must be false (which we check above): // "std::numeric_limits<size_t>::max() / 2 < static_cast<size_t>(countCuts) - 1" EBM_ASSERT(!IsAddError(static_cast<size_t>(low), static_cast<size_t>(high))); middle = (static_cast<size_t>(low) + static_cast<size_t>(high)) >> 1; EBM_ASSERT(middle <= static_cast<size_t>(high)); EBM_ASSERT(middle < static_cast<size_t>(countCuts)); midVal = cutsLowerBoundInclusive[middle]; EBM_ASSERT(middle < size_t { std::numeric_limits<ptrdiff_t>::max() }); low = UNPREDICTABLE(midVal <= featureValue) ? static_cast<ptrdiff_t>(middle) + ptrdiff_t { 1 } : low; EBM_ASSERT(ptrdiff_t { 0 } <= low && static_cast<size_t>(low) <= static_cast<size_t>(countCuts)); high = UNPREDICTABLE(midVal <= featureValue) ? high : static_cast<ptrdiff_t>(middle) - ptrdiff_t { 1 }; EBM_ASSERT(ptrdiff_t { -1 } <= high && high <= highStart); // high can become -1 in some cases, so it needs to be ptrdiff_t. It's tempting to try and change // this code and use the Hermann Bottenbruch version that checks for low != high in the loop comparison // since then we wouldn't have negative values and we could use size_t, but unfortunately that version // has a check at the end where we'd need to fetch cutsLowerBoundInclusive[low] after exiting the // loop, so this version we have here is faster given that we only need to compare to a value that // we've already fetched from memory. Also, this version makes slightly faster progress since // it does middle + 1 AND middle - 1 instead of just middle - 1, so it often eliminates one loop // iteration. In practice this version will always work since no floating point type is less than 4 // bytes, so we shouldn't have difficulty expressing any indexes with ptrdiff_t, and our indexes // for accessing memory are always size_t, so those should always work. } while(LIKELY(low <= high)); EBM_ASSERT(size_t { 0 } <= middle && middle < static_cast<size_t>(countCuts)); middle = UNPREDICTABLE(midVal <= featureValue) ? middle + size_t { 2 } : middle + size_t { 1 }; EBM_ASSERT(size_t { 1 } <= middle && middle <= size_t { 1 } + static_cast<size_t>(countCuts)); EBM_ASSERT(!IsConvertError<IntEbmType>(middle)); return static_cast<IntEbmType>(middle); } // don't bother using a lock here. We don't care if an extra log message is written out due to thread parallism static int g_cLogEnterDiscretizeParametersMessages = 25; static int g_cLogExitDiscretizeParametersMessages = 25; EBM_NATIVE_IMPORT_EXPORT_BODY ErrorEbmType EBM_NATIVE_CALLING_CONVENTION Discretize( IntEbmType countSamples, const FloatEbmType * featureValues, IntEbmType countCuts, const FloatEbmType * cutsLowerBoundInclusive, IntEbmType * discretizedOut ) { // make the 0th bin always the missing value. This makes cutting mains easier, since we always know where the // missing bin will be, and also the first non-missing bin. We can also increment the pointer to the histogram // to the first non-missing bin and reduce our bin index numbers by one, which will allow us to compress // binary features into 1 bit still. It will make handling tensors with missing or no missing easier since // we'll always know how to skip the missing slice if desired. None of these things are as easy if the missing // bin is in the Nth item because we then need to know what N is and use multiplication and badly ordered memory // accesses to reach it if we want to use the missing bin during cutting. Lastly, in higher level languages, it's // easier to detect missing values in the discretized data, since it's always just in index zero. // Finally, the way we compute our tensor sums allows us to calculate a slice of the tensor at the 0th index // with just a single check, so having the missing value at the 0th index allows fast lookup of the missing values // so we can do things like try putting the missing values into the left and right statistics of any cuts easily // // this function has exactly the same behavior as numpy.digitize, including the lower bound inclusive semantics // TODO: we want this function super-fast to handle the case where someone calls Discretize repeatedly // once per-sample. We can make this faster by eliminating a lot of the initial checks by: // - eliminate the checks for nullptr on our input points. We just crash if we get these illegal inputs // we can't handle bad input points in general, so this is just accepting a reality for a tradeoff in speed // - create a function that converts any signed value into the proper unsigned value // we can do this using std::make_unsigned to find the type and then use the twos compliment // trick in RandomStream to convert the signed value into the corresponding unsigned value // (also replace the code in RandomStream with this new function). This function will be // a no-op in assembly. // - we check for both negative AND positive countCuts values that are too high. We can // combine these checks by first converting negatives into big positive unsigned values // which are guaranteed to be larger than our largest valid index. We then find via // constexpr the biggest of the maxes that we care about, and then make one comparison // for all these conditions. We might have code that differentiates the results if we trigger // an error return // - we have comparisons to both size_t and IntEbmType max values, which we can collapse into // just a single max value comparison. If the max unsigned size_t is bigger than the max unsigned // UIntEbmType then do the comparison in the bigger domain. // - we can write a constexpr function that takes the value we have, and the max value in // the same type and the max value in annother type and does all the right things to compare // them properly. Use SINAFE to have 2 functions (one where the initial value type is lower // and another where it is higher). We could probably use this function in a number of places // - special case a function that handles when countSamples is 1 and make the check at the top // since getting just 1 sample is going to be the norm a lot. In that case it doesn't // make sense to check all the other possible values or copy the cuts to new memory or use SIMD // we can even eliminate the loop stuff we construct to handle multiple samples and just write // directly to the pointers // - we'll probably need to check countCuts for zero, which we can do by first converting it // to unsigned, then decrementing it (which is legal in C++) to a huge number if it was zero // then doing our upper bound comparison all in one check. We can then filter our 0 ==countCuts // after that as a special case LOG_COUNTED_N( &g_cLogEnterDiscretizeParametersMessages, TraceLevelInfo, TraceLevelVerbose, "Entered Discretize: " "countSamples=%" IntEbmTypePrintf ", " "featureValues=%p, " "countCuts=%" IntEbmTypePrintf ", " "cutsLowerBoundInclusive=%p, " "discretizedOut=%p" , countSamples, static_cast<const void *>(featureValues), countCuts, static_cast<const void *>(cutsLowerBoundInclusive), static_cast<void *>(discretizedOut) ); ErrorEbmType error; if(UNLIKELY(countSamples <= IntEbmType { 0 })) { if(UNLIKELY(countSamples < IntEbmType { 0 })) { LOG_0(TraceLevelError, "ERROR Discretize countSamples cannot be negative"); error = Error_IllegalParamValue; goto exit_with_log; } else { EBM_ASSERT(IntEbmType { 0 } == countSamples); error = Error_None; goto exit_with_log; } } else { if(UNLIKELY(IsConvertError<size_t>(countSamples))) { // this needs to point to real memory, otherwise it's invalid LOG_0(TraceLevelError, "ERROR Discretize countSamples was too large to fit into memory"); error = Error_IllegalParamValue; goto exit_with_log; } const size_t cSamples = static_cast<size_t>(countSamples); if(IsMultiplyError(sizeof(*featureValues), cSamples)) { LOG_0(TraceLevelError, "ERROR Discretize countSamples was too large to fit into featureValues"); error = Error_IllegalParamValue; goto exit_with_log; } if(IsMultiplyError(sizeof(*discretizedOut), cSamples)) { LOG_0(TraceLevelError, "ERROR Discretize countSamples was too large to fit into discretizedOut"); error = Error_IllegalParamValue; goto exit_with_log; } if(UNLIKELY(nullptr == featureValues)) { LOG_0(TraceLevelError, "ERROR Discretize featureValues cannot be null"); error = Error_IllegalParamValue; goto exit_with_log; } if(UNLIKELY(nullptr == discretizedOut)) { LOG_0(TraceLevelError, "ERROR Discretize discretizedOut cannot be null"); error = Error_IllegalParamValue; goto exit_with_log; } const FloatEbmType * pValue = featureValues; const FloatEbmType * const pValueEnd = featureValues + cSamples; IntEbmType * pDiscretized = discretizedOut; if(UNLIKELY(countCuts <= IntEbmType { 0 })) { if(UNLIKELY(countCuts < IntEbmType { 0 })) { LOG_0(TraceLevelError, "ERROR Discretize countCuts cannot be negative"); error = Error_IllegalParamValue; goto exit_with_log; } EBM_ASSERT(IntEbmType { 0 } == countCuts); do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : IntEbmType { 1 }; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(UNLIKELY(nullptr == cutsLowerBoundInclusive)) { LOG_0(TraceLevelError, "ERROR Discretize cutsLowerBoundInclusive cannot be null"); error = Error_IllegalParamValue; goto exit_with_log; } #ifndef NDEBUG if(!IsConvertError<size_t>(countCuts)) { const size_t cCuts = static_cast<size_t>(countCuts); size_t iDebug = 0; while(true) { EBM_ASSERT(!std::isnan(cutsLowerBoundInclusive[iDebug])); EBM_ASSERT(!std::isinf(cutsLowerBoundInclusive[iDebug])); size_t iDebugInc = iDebug + 1; if(cCuts <= iDebugInc) { break; } // if the values aren't increasing, we won't crash, but we'll return non-sensical bins. That's a tollerable // failure though given that this check might be expensive if cCuts was large compared to cSamples EBM_ASSERT(cutsLowerBoundInclusive[iDebug] < cutsLowerBoundInclusive[iDebugInc]); iDebug = iDebugInc; } } # endif // NDEBUG if(PREDICTABLE(IntEbmType { 1 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(PREDICTABLE(IntEbmType { 2 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; const FloatEbmType cut1 = cutsLowerBoundInclusive[1]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(cut1 <= val) ? IntEbmType { 3 } : result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(PREDICTABLE(IntEbmType { 3 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; const FloatEbmType cut1 = cutsLowerBoundInclusive[1]; const FloatEbmType cut2 = cutsLowerBoundInclusive[2]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(cut1 <= val) ? IntEbmType { 3 } : result; result = UNPREDICTABLE(cut2 <= val) ? IntEbmType { 4 } : result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(PREDICTABLE(IntEbmType { 4 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; const FloatEbmType cut1 = cutsLowerBoundInclusive[1]; const FloatEbmType cut2 = cutsLowerBoundInclusive[2]; const FloatEbmType cut3 = cutsLowerBoundInclusive[3]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(cut1 <= val) ? IntEbmType { 3 } : result; result = UNPREDICTABLE(cut2 <= val) ? IntEbmType { 4 } : result; result = UNPREDICTABLE(cut3 <= val) ? IntEbmType { 5 } : result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(PREDICTABLE(IntEbmType { 5 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; const FloatEbmType cut1 = cutsLowerBoundInclusive[1]; const FloatEbmType cut2 = cutsLowerBoundInclusive[2]; const FloatEbmType cut3 = cutsLowerBoundInclusive[3]; const FloatEbmType cut4 = cutsLowerBoundInclusive[4]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(cut1 <= val) ? IntEbmType { 3 } : result; result = UNPREDICTABLE(cut2 <= val) ? IntEbmType { 4 } : result; result = UNPREDICTABLE(cut3 <= val) ? IntEbmType { 5 } : result; result = UNPREDICTABLE(cut4 <= val) ? IntEbmType { 6 } : result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } if(PREDICTABLE(IntEbmType { 6 } == countCuts)) { const FloatEbmType cut0 = cutsLowerBoundInclusive[0]; const FloatEbmType cut1 = cutsLowerBoundInclusive[1]; const FloatEbmType cut2 = cutsLowerBoundInclusive[2]; const FloatEbmType cut3 = cutsLowerBoundInclusive[3]; const FloatEbmType cut4 = cutsLowerBoundInclusive[4]; const FloatEbmType cut5 = cutsLowerBoundInclusive[5]; do { const FloatEbmType val = *pValue; IntEbmType result; result = UNPREDICTABLE(cut0 <= val) ? IntEbmType { 2 } : IntEbmType { 1 }; result = UNPREDICTABLE(cut1 <= val) ? IntEbmType { 3 } : result; result = UNPREDICTABLE(cut2 <= val) ? IntEbmType { 4 } : result; result = UNPREDICTABLE(cut3 <= val) ? IntEbmType { 5 } : result; result = UNPREDICTABLE(cut4 <= val) ? IntEbmType { 6 } : result; result = UNPREDICTABLE(cut5 <= val) ? IntEbmType { 7 } : result; result = UNPREDICTABLE(std::isnan(val)) ? IntEbmType { 0 } : result; EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } FloatEbmType cutsLowerBoundInclusiveCopy[1023]; // the only value that should be less than this one is NaN, which always returns false for comparisons // that are not NaN. If we have a NaN value we expect this to convert us to the 0th bin for missing cutsLowerBoundInclusiveCopy[0] = -std::numeric_limits<FloatEbmType>::infinity(); // it's always legal in C++ to convert a signed value to unsigned. We check below for out of bounds if needed const size_t cCuts = static_cast<size_t>(countCuts); if(PREDICTABLE(countCuts <= IntEbmType { 14 })) { constexpr size_t cPower = 16; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 30 })) { constexpr size_t cPower = 32; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 62 })) { constexpr size_t cPower = 64; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 15 } * sizeof(FloatEbmType)) <= val) ? size_t { 16 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 126 })) { constexpr size_t cPower = 128; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 31 } * sizeof(FloatEbmType)) <= val) ? size_t { 32 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 15 } * sizeof(FloatEbmType)) <= val) ? size_t { 16 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 254 })) { constexpr size_t cPower = 256; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 63 } * sizeof(FloatEbmType)) <= val) ? size_t { 64 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 31 } * sizeof(FloatEbmType)) <= val) ? size_t { 32 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 15 } * sizeof(FloatEbmType)) <= val) ? size_t { 16 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 510 })) { constexpr size_t cPower = 512; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 <= sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 127 } * sizeof(FloatEbmType)) <= val) ? size_t { 128 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 63 } * sizeof(FloatEbmType)) <= val) ? size_t { 64 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 31 } * sizeof(FloatEbmType)) <= val) ? size_t { 32 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 15 } * sizeof(FloatEbmType)) <= val) ? size_t { 16 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } else if(PREDICTABLE(countCuts <= IntEbmType { 1022 })) { constexpr size_t cPower = 1024; if(cPower * 4 <= cSamples) { static_assert(cPower - 1 == sizeof(cutsLowerBoundInclusiveCopy) / sizeof(cutsLowerBoundInclusiveCopy[0]), "cutsLowerBoundInclusiveCopy buffer not large enough"); memcpy( size_t { 1 } + cutsLowerBoundInclusiveCopy, cutsLowerBoundInclusive, sizeof(*cutsLowerBoundInclusive) * cCuts ); if(LIKELY(cCuts != cPower - size_t { 2 })) { FloatEbmType * pFill = &cutsLowerBoundInclusiveCopy[cCuts + size_t { 1 }]; const FloatEbmType * const pEndFill = &cutsLowerBoundInclusiveCopy[cPower - size_t { 1 }]; do { // NaN will always move us downwards into the region of valid cuts. The first cut is always // guaranteed to be non-NaN, so if we have a missing (NaN) value, then the binary search will // go low first and never hit these upper NaN values. *pFill = std::numeric_limits<FloatEbmType>::quiet_NaN(); ++pFill; } while(LIKELY(pEndFill != pFill)); } const FloatEbmType firstComparison = cutsLowerBoundInclusiveCopy[cPower / 2 - 1]; do { const FloatEbmType val = *pValue; char * pResult = reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy); pResult += UNPREDICTABLE(firstComparison <= val) ? size_t { cPower / 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 255 } * sizeof(FloatEbmType)) <= val) ? size_t { 256 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 127 } * sizeof(FloatEbmType)) <= val) ? size_t { 128 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 63 } * sizeof(FloatEbmType)) <= val) ? size_t { 64 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 31 } * sizeof(FloatEbmType)) <= val) ? size_t { 32 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 15 } * sizeof(FloatEbmType)) <= val) ? size_t { 16 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 7 } * sizeof(FloatEbmType)) <= val) ? size_t { 8 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 3 } * sizeof(FloatEbmType)) <= val) ? size_t { 4 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult + size_t { 1 } * sizeof(FloatEbmType)) <= val) ? size_t { 2 } * sizeof(FloatEbmType) : size_t { 0 }; pResult += UNPREDICTABLE(*reinterpret_cast<FloatEbmType *>(pResult) <= val) ? size_t { 1 } * sizeof(FloatEbmType) : size_t { 0 }; const size_t result = (pResult - reinterpret_cast<char *>(cutsLowerBoundInclusiveCopy)) / sizeof(FloatEbmType); EBM_ASSERT(static_cast<IntEbmType>(result) == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = static_cast<IntEbmType>(result); ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; goto exit_with_log; } } if(UNLIKELY(IsConvertError<size_t>(countCuts))) { // this needs to point to real memory, otherwise it's invalid LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to fit into memory"); error = Error_IllegalParamValue; // the cutsLowerBoundInclusive wouldn't be possible goto exit_with_log; } if(IsMultiplyError(sizeof(*cutsLowerBoundInclusive), cCuts)) { LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to fit into cutsLowerBoundInclusive"); error = Error_IllegalParamValue; // the cutsLowerBoundInclusive array wouldn't be possible goto exit_with_log; } if(UNLIKELY(std::numeric_limits<IntEbmType>::max() - IntEbmType { 2 } < countCuts)) { // IntEbmType::max should be the maximum number of bins that we allow. This prevents our caller from accidentally // overflowing when using either the count (eg: 255) or the index (eg: 0-254). The 0th bin is the special missing // bin, so we have max - 1 normal bins. We have 1 less cuts than we have bins (1 cut means 2 bins), so we can // have a maximum of max - 2 cuts. LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to allow for a missing value placeholder and -+inf bins"); // this is a non-overflow somewhat arbitrary number for the upper level software to understand // so instead of returning illegal parameter, we should return out of memory and pretend that we // tried to allocate it since it doesn't seem worth creating a new error class for it error = Error_OutOfMemory; goto exit_with_log; } if(UNLIKELY(std::numeric_limits<size_t>::max() == cCuts)) { // we add 1 to cCuts as our missing value, so this addition must succeed LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to allow for a missing value placeholder"); // this is a non-overflow somewhat arbitrary number for the upper level software to understand // so instead of returning illegal parameter, we should return out of memory and pretend that we // tried to allocate it since it doesn't seem worth creating a new error class for it error = Error_OutOfMemory; goto exit_with_log; } if(UNLIKELY(size_t { std::numeric_limits<ptrdiff_t>::max() } < cCuts)) { // the low value can increase until it's equal to cCuts, so cCuts must be expressable as a ptrdiff_t // we need to keep low as a ptrdiff_t since we compare it right after with high, which can be -1 LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to allow for the binary search comparison"); // this is a non-overflow somewhat arbitrary number for the upper level software to understand // so instead of returning illegal parameter, we should return out of memory and pretend that we // tried to allocate it since it doesn't seem worth creating a new error class for it error = Error_OutOfMemory; goto exit_with_log; } if(UNLIKELY(std::numeric_limits<size_t>::max() / size_t { 2 } + size_t { 1 } < cCuts)) { // our first operation towards getting the mid-point is to add the size_t low and size_t high, and that can't // overflow, so check that the maximum high added to the maximum low (which is the high) don't exceed that value LOG_0(TraceLevelError, "ERROR Discretize countCuts was too large to allow for the binary search add"); // this is a non-overflow somewhat arbitrary number for the upper level software to understand // so instead of returning illegal parameter, we should return out of memory and pretend that we // tried to allocate it since it doesn't seem worth creating a new error class for it error = Error_OutOfMemory; goto exit_with_log; } EBM_ASSERT(cCuts < std::numeric_limits<size_t>::max()); EBM_ASSERT(size_t { 1 } <= cCuts); EBM_ASSERT(cCuts <= size_t { std::numeric_limits<ptrdiff_t>::max() }); const ptrdiff_t highStart = static_cast<ptrdiff_t>(cCuts) - ptrdiff_t { 1 }; // if we're going to runroll our first loop, then we need to ensure that there's a next loop after the first // unrolled loop, otherwise we would need to check if we were done before the first real loop iteration. // To ensure we have 2 original loop iterations, we need 1 cut in the center, 1 cut above, and 1 cut below, so 3 EBM_ASSERT(size_t { 3 } <= cCuts); const size_t firstMiddle = static_cast<size_t>(highStart) >> 1; EBM_ASSERT(firstMiddle < cCuts); const FloatEbmType firstMidVal = cutsLowerBoundInclusive[firstMiddle]; const ptrdiff_t firstMidLow = static_cast<ptrdiff_t>(firstMiddle) + ptrdiff_t { 1 }; const ptrdiff_t firstMidHigh = static_cast<ptrdiff_t>(firstMiddle) - ptrdiff_t { 1 }; do { const FloatEbmType val = *pValue; size_t middle = size_t { 0 }; if(PREDICTABLE(!std::isnan(val))) { ptrdiff_t high = UNPREDICTABLE(firstMidVal <= val) ? highStart : firstMidHigh; ptrdiff_t low = UNPREDICTABLE(firstMidVal <= val) ? firstMidLow : ptrdiff_t { 0 }; FloatEbmType midVal; do { EBM_ASSERT(ptrdiff_t { 0 } <= low && static_cast<size_t>(low) < cCuts); EBM_ASSERT(ptrdiff_t { 0 } <= high && static_cast<size_t>(high) < cCuts); EBM_ASSERT(low <= high); // low is equal or lower than high, so summing them can't exceed 2 * high, and after division it // can't be higher than high, so middle can't overflow ptrdiff_t after the division since high // is already a ptrdiff_t. Generally the maximum positive value of a ptrdiff_t can be doubled // when converted to a size_t, although that isn't guaranteed. A more correct statement is that // the following must be false (which we check above): // "std::numeric_limits<size_t>::max() / 2 < cCuts - 1" EBM_ASSERT(!IsAddError(static_cast<size_t>(low), static_cast<size_t>(high))); middle = (static_cast<size_t>(low) + static_cast<size_t>(high)) >> 1; EBM_ASSERT(middle <= static_cast<size_t>(high)); EBM_ASSERT(middle < cCuts); midVal = cutsLowerBoundInclusive[middle]; EBM_ASSERT(middle < size_t { std::numeric_limits<ptrdiff_t>::max() }); low = UNPREDICTABLE(midVal <= val) ? static_cast<ptrdiff_t>(middle) + ptrdiff_t { 1 } : low; EBM_ASSERT(ptrdiff_t { 0 } <= low && static_cast<size_t>(low) <= cCuts); high = UNPREDICTABLE(midVal <= val) ? high : static_cast<ptrdiff_t>(middle) - ptrdiff_t { 1 }; EBM_ASSERT(ptrdiff_t { -1 } <= high && high <= highStart); // high can become -1 in some cases, so it needs to be ptrdiff_t. It's tempting to try and change // this code and use the Hermann Bottenbruch version that checks for low != high in the loop comparison // since then we wouldn't have negative values and we could use size_t, but unfortunately that version // has a check at the end where we'd need to fetch cutsLowerBoundInclusive[low] after exiting the // loop, so this version we have here is faster given that we only need to compare to a value that // we've already fetched from memory. Also, this version makes slightly faster progress since // it does middle + 1 AND middle - 1 instead of just middle - 1, so it often eliminates one loop // iteration. In practice this version will always work since no floating point type is less than 4 // bytes, so we shouldn't have difficulty expressing any indexes with ptrdiff_t, and our indexes // for accessing memory are always size_t, so those should always work. } while(LIKELY(low <= high)); EBM_ASSERT(size_t { 0 } <= middle && middle < cCuts); middle = UNPREDICTABLE(midVal <= val) ? middle + size_t { 2 } : middle + size_t { 1 }; EBM_ASSERT(size_t { 1 } <= middle && middle <= size_t { 1 } + cCuts); } EBM_ASSERT(!IsConvertError<IntEbmType>(middle)); const IntEbmType result = static_cast<IntEbmType>(middle); EBM_ASSERT(result == DiscretizeOne(val, countCuts, cutsLowerBoundInclusive)); *pDiscretized = result; ++pDiscretized; ++pValue; } while(LIKELY(pValueEnd != pValue)); error = Error_None; } exit_with_log:; LOG_COUNTED_N( &g_cLogExitDiscretizeParametersMessages, TraceLevelInfo, TraceLevelVerbose, "Exited Discretize: " "return=%" ErrorEbmTypePrintf , error ); return error; } } // DEFINED_ZONE_NAME
// Problem Code: 1269B #include <iostream> #include <vector> #include <limits> #include <algorithm> using namespace std; int modulo_equality(int n, int m, vector<int>& a, vector<int>& b) { int i, j, d, min_d = numeric_limits<int>::max(); sort(a.begin(), a.end()); sort(b.begin(), b.end()); for (int k = 0; k < n; k++) { d = (m - a[0] + b[k]) % m; for (i = 0, j = k; i < n; i++, j = (j + 1) % n) if ((a[i] + d) % m != b[j]) break; if (i == n) min_d = min(d, min_d); } return min_d; } int main() { int n, m; cin >> n >> m; vector<int> a(n), b(n); for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) cin >> b[i]; cout << modulo_equality(n, m, a, b); return 0; }
/* * Copyright (c) 2016 Regents of the University of California. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * *********************************************************************************************** * * CARLsim * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran * maintained by: * (MA) Mike Avery <averym@uci.edu> * (MB) Michael Beyeler <mbeyeler@uci.edu>, * (KDC) Kristofor Carlson <kdcarlso@uci.edu> * (TSC) Ting-Shuo Chou <tingshuc@uci.edu> * (HK) Hirak J Kashyap <kashyaph@uci.edu> * * CARLsim v1.0: JM, MDR * CARLsim v2.0/v2.1/v2.2: JM, MDR, MA, MB, KDC * CARLsim3: MB, KDC, TSC * CARLsim4: TSC, HK * CARLsim5: HK, JX, KC * CARLsim6: LN, JX, KC, KW * * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/ * Ver 12/31/2016 */ #include <carlsim.h> #include <user_errors.h> //#include <callback.h> #include <callback_core.h> #include <iostream> // std::cout, std::endl #include <sstream> // std::stringstream #include <algorithm> // std::find, std::transform #include <snn.h> // includes for mkdir #if CREATE_SPIKEDIR_IF_NOT_EXISTS #if defined(WIN32) || defined(WIN64) #else #include <sys/stat.h> #include <errno.h> #include <libgen.h> #endif #endif // NOTE: Conceptual code documentation should go in carlsim.h. Do not include extensive high-level documentation here, // but do document your code. class CARLsim::Impl { public: // +++++ PUBLIC METHODS: SETUP / TEAR-DOWN ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // Impl(CARLsim* sim, const std::string& netName, SimMode prferredSimMode, LoggerMode loggerMode, int randSeed) { netName_ = netName; loggerMode_ = loggerMode; preferredSimMode_ = prferredSimMode; randSeed_ = randSeed; enablePrint_ = false; copyState_ = false; numConnections_ = 0; hasSetHomeoALL_ = false; hasSetHomeoBaseFiringALL_ = false; hasSetSTDPALL_ = false; hasSetSTPALL_ = false; hasSetConductances_ = false; carlsimState_ = CONFIG_STATE; sim_ = sim; snn_ = NULL; CARLsimInit(); // move everything else out of constructor } ~Impl() { // save simulation if (carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE) saveSimulation(def_save_fileName_,def_save_synapseInfo_); //\issue: LN20201021: certainly _NOT_ in the desctructor - review this following the user manual regarding open file pointers // deallocate all dynamically allocated structures for (int i=0; i<spkGen_.size(); i++) { if (spkGen_[i]!=NULL) delete spkGen_[i]; spkGen_[i]=NULL; } for (int i=0; i<connGen_.size(); i++) { if (connGen_[i]!=NULL) delete connGen_[i]; connGen_[i]=NULL; } if (snn_!=NULL) delete snn_; snn_=NULL; } //#ifdef __LN_EXT__ // // // LN Extension 20201017 // int cudaDeviceCount() { // return snn_->cudaDeviceCount(); // } // // // LN Extension 20201017 // void cudaDeviceDescription(unsigned ithGPU, const char **desc) { // snn_->cudaDeviceDescription(ithGPU, desc); // } // //#endif // +++++++++ PUBLIC METHODS: SETTING UP A SIMULATION ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // Connects a presynaptic to a postsynaptic group using one of the primitive types short int connect(int grpId1, int grpId2, const std::string& connType, const RangeWeight& wt, float connProb, const RangeDelay& delay, const RadiusRF& radRF, bool synWtType, float mulSynFast, float mulSynSlow) { std::string funcName = "connect(\""+getGroupName(grpId1)+"\",\""+getGroupName(grpId2)+"\")"; std::stringstream grpId1str; grpId1str << "Group Id " << grpId1; std::stringstream grpId2str; grpId2str << "Group Id " << grpId2; UserErrors::assertTrue(grpId1!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId1str.str()); // grpId can't be ALL UserErrors::assertTrue(grpId2!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId2str.str()); UserErrors::assertTrue(!isPoissonGroup(grpId2), UserErrors::WRONG_NEURON_TYPE, funcName, grpId2str.str() + " is PoissonGroup, connect"); UserErrors::assertTrue(wt.max>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "wt.max"); UserErrors::assertTrue(wt.min>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "wt.min"); UserErrors::assertTrue(wt.init>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "wt.init"); UserErrors::assertTrue(connProb>=0.0f && connProb<=1.0f, UserErrors::MUST_BE_IN_RANGE, funcName, "Connection Probability connProb", "[0,1]"); UserErrors::assertTrue(delay.min>0, UserErrors::MUST_BE_POSITIVE, funcName, "delay.min"); UserErrors::assertTrue(connType.compare("one-to-one")!=0 || connType.compare("one-to-one")==0 && getGroupNumNeurons(grpId1) == getGroupNumNeurons(grpId2), UserErrors::MUST_BE_IDENTICAL, funcName, "For type \"one-to-one\", number of neurons in pre and post"); UserErrors::assertTrue(connType.compare("gaussian")!=0 || connType.compare("gaussian")==0 && (radRF.radX>-1 || radRF.radY>-1 || radRF.radZ>-1), UserErrors::CANNOT_BE_NEGATIVE, funcName, "Receptive field radius for type \"gaussian\""); UserErrors::assertTrue(synWtType==SYN_PLASTIC || synWtType==SYN_FIXED && wt.init==wt.max, UserErrors::MUST_BE_IDENTICAL, funcName, "For fixed synapses, initWt and maxWt"); UserErrors::assertTrue(mulSynFast>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "mulSynFast"); UserErrors::assertTrue(mulSynSlow>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "mulSynSlow"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); assert(++numConnections_ <= MAX_CONN_PER_SNN); // throw a warning if "one-to-one" is used in combination with a non-zero RF if (connType.compare("one-to-one")==0 && (radRF.radX>0 || radRF.radY>0 || radRF.radZ>0)) { userWarnings_.push_back("RadiusRF>0 will be ignored for connection type \"one-to-one\""); } // TODO: enable support for non-zero min if (fabs(wt.min)>1e-15) { std::cerr << funcName << ": " << wt << ". Non-zero minimum weights are not yet supported.\n" << std::endl; assert(false); } // groups cannot be both chemically (synaptically) and electrically (compartmentally) connected UserErrors::assertTrue(std::find(connComp_[grpId1].begin(), connComp_[grpId1].end(), grpId2) == connComp_[grpId1].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); UserErrors::assertTrue(std::find(connComp_[grpId2].begin(), connComp_[grpId2].end(), grpId1) == connComp_[grpId2].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); // add synaptic connection to 2D matrix connSyn_[grpId1].push_back(grpId2); return snn_->connect(grpId1, grpId2, connType, wt.init, wt.max, connProb, delay.min, delay.max, radRF, mulSynFast, mulSynSlow, synWtType); } // custom connectivity profile short int connect(int grpId1, int grpId2, ConnectionGenerator* conn, bool synWtType) { std::string funcName = "connect(\""+getGroupName(grpId1)+"\",\""+getGroupName(grpId2)+"\")"; std::stringstream grpId1str; grpId1str << ". Group Id " << grpId1; std::stringstream grpId2str; grpId2str << ". Group Id " << grpId2; UserErrors::assertTrue(grpId1!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId1str.str()); // grpId can't be ALL UserErrors::assertTrue(grpId2!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId2str.str()); UserErrors::assertTrue(!isPoissonGroup(grpId2), UserErrors::WRONG_NEURON_TYPE, funcName, grpId2str.str() + " is PoissonGroup, connect"); UserErrors::assertTrue(conn!=NULL, UserErrors::CANNOT_BE_NULL, funcName, "ConnectionGenerator* conn"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); assert(++numConnections_ <= MAX_CONN_PER_SNN); // groups cannot be both chemically (synaptically) and electrically (compartmentally) connected UserErrors::assertTrue(std::find(connComp_[grpId1].begin(), connComp_[grpId1].end(), grpId2) == connComp_[grpId1].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); UserErrors::assertTrue(std::find(connComp_[grpId2].begin(), connComp_[grpId2].end(), grpId1) == connComp_[grpId2].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); // add synaptic connection to 2D matrix connSyn_[grpId1].push_back(grpId2); // TODO: check for sign of weights // ConnectionGeneratorCore* CGC = new ConnectionGeneratorCore(this, conn); ConnectionGeneratorCore* CGC = new ConnectionGeneratorCore(sim_, conn); connGen_.push_back(CGC); return snn_->connect(grpId1, grpId2, CGC, 1.0f, 1.0f, synWtType); } // custom connectivity profile short int connect(int grpId1, int grpId2, ConnectionGenerator* conn, float mulSynFast, float mulSynSlow, bool synWtType) { std::string funcName = "connect(\""+getGroupName(grpId1)+"\",\""+getGroupName(grpId2)+"\")"; std::stringstream grpId1str; grpId1str << ". Group Id " << grpId1; std::stringstream grpId2str; grpId2str << ". Group Id " << grpId2; UserErrors::assertTrue(grpId1!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId1str.str()); // grpId can't be ALL UserErrors::assertTrue(grpId2!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, grpId2str.str()); UserErrors::assertTrue(!isPoissonGroup(grpId2), UserErrors::WRONG_NEURON_TYPE, funcName, grpId2str.str() + " is PoissonGroup, connect"); UserErrors::assertTrue(conn!=NULL, UserErrors::CANNOT_BE_NULL, funcName); UserErrors::assertTrue(mulSynFast>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "mulSynFast"); UserErrors::assertTrue(mulSynSlow>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName, "mulSynSlow"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); assert(++numConnections_ <= MAX_CONN_PER_SNN); // groups cannot be both chemically (synaptically) and electrically (compartmentally) connected UserErrors::assertTrue(std::find(connComp_[grpId1].begin(), connComp_[grpId1].end(), grpId2) == connComp_[grpId1].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); UserErrors::assertTrue(std::find(connComp_[grpId2].begin(), connComp_[grpId2].end(), grpId1) == connComp_[grpId2].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName, grpId1str.str() + " and " + grpId2str.str()); // add synaptic connection to 2D matrix connSyn_[grpId1].push_back(grpId2); // ConnectionGeneratorCore* CGC = new ConnectionGeneratorCore(this, conn); ConnectionGeneratorCore* CGC = new ConnectionGeneratorCore(sim_, conn); connGen_.push_back(CGC); return snn_->connect(grpId1, grpId2, CGC, mulSynFast, mulSynSlow, synWtType); } short int connectCompartments(int grpIdLower, int grpIdUpper) { std::stringstream funcName; funcName << "connectCompartments(" << grpIdLower << "," << grpIdUpper << ")"; // grpIDs must be valid, cannot be identical std::stringstream grpIdLowerStr; grpIdLowerStr << "Group Id " << grpIdLower; std::stringstream grpIdUpperStr; grpIdUpperStr << "Group Id " << grpIdUpper; UserErrors::assertTrue(grpIdLower >= 0 && grpIdLower<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), grpIdLowerStr.str(), "[0,getNumGroups()]"); UserErrors::assertTrue(grpIdUpper >= 0 && grpIdUpper<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), grpIdUpperStr.str(), "[0,getNumGroups()]"); UserErrors::assertTrue(grpIdLower != grpIdUpper, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); // groups cannot be spike generators UserErrors::assertTrue(!isPoissonGroup(grpIdLower), UserErrors::WRONG_NEURON_TYPE, funcName.str(), grpIdLowerStr.str() + " is PoissonGroup, connectCompartments"); UserErrors::assertTrue(!isPoissonGroup(grpIdUpper), UserErrors::WRONG_NEURON_TYPE, funcName.str(), grpIdUpperStr.str() + " is PoissonGroup, connectCompartments"); // groups must have the same size UserErrors::assertTrue(getGroupNumNeurons(grpIdLower) == getGroupNumNeurons(grpIdUpper), UserErrors::MUST_BE_IDENTICAL, funcName.str(), "Sizes of " + grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); // groups must be located on the same partition UserErrors::assertTrue(groupPrefNetIds_.at(grpIdLower) == groupPrefNetIds_.at(grpIdUpper), UserErrors::MUST_BE_IDENTICAL, funcName.str(), "Preferred partions of " + grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); // groups cannot be both chemically (synaptically) and electrically (compartmentally) connected UserErrors::assertTrue(std::find(connSyn_[grpIdLower].begin(), connSyn_[grpIdLower].end(), grpIdUpper) == connSyn_[grpIdLower].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName.str(), grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); UserErrors::assertTrue(std::find(connSyn_[grpIdUpper].begin(), connSyn_[grpIdUpper].end(), grpIdLower) == connSyn_[grpIdUpper].end(), UserErrors::CANNOT_BE_CONN_SYN_AND_COMP, funcName.str(), grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); // groups cannot be connected twice (order doesn't matter) UserErrors::assertTrue(std::find(connComp_[grpIdLower].begin(), connComp_[grpIdLower].end(), grpIdUpper) == connComp_[grpIdLower].end(), UserErrors::CANNOT_BE_CONN_TWICE, funcName.str(), grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); UserErrors::assertTrue(std::find(connComp_[grpIdUpper].begin(), connComp_[grpIdUpper].end(), grpIdLower) == connComp_[grpIdUpper].end(), UserErrors::CANNOT_BE_CONN_TWICE, funcName.str(), grpIdLowerStr.str() + " and " + grpIdUpperStr.str()); // groups can have at most getMaxNumCompConnections() connections UserErrors::assertTrue(connComp_[grpIdLower].size() < getMaxNumCompConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "Number of compartmental connections for group " + grpIdLowerStr.str(), "[0,getMaxNumCompConnections()"); UserErrors::assertTrue(connComp_[grpIdUpper].size() < getMaxNumCompConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "Number of compartmental connections for group " + grpIdUpperStr.str(), "[0,getMaxNumCompConnections()"); // add compartment connection to 2D matrix (both ways) connComp_[grpIdLower].push_back(grpIdUpper); connComp_[grpIdUpper].push_back(grpIdLower); return snn_->connectCompartments(grpIdLower, grpIdUpper); } // create group of Izhikevich spiking neurons on 1D grid int createGroup(const std::string& grpName, int nNeur, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return createGroup(grpName, Grid3D(nNeur,1,1), neurType, preferredPartition, preferredBackend); } // create group of LIF spiking neurons on 1D grid int createGroupLIF(const std::string& grpName, int nNeur, int neurType, int preferredPartition = ANY, ComputingBackend preferredBackend = CPU_CORES){ return createGroupLIF(grpName, Grid3D(nNeur,1,1), neurType, preferredPartition, preferredBackend); } // create a group of Izhikevich spiking neurons on 3D grid int createGroup(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { std::string funcName = "createGroup(\""+grpName+"\")"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(grid.numX>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numX"); UserErrors::assertTrue(grid.numY>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numY"); UserErrors::assertTrue(grid.numZ>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numZ"); // if user has called any set functions with grpId=ALL, and is now adding another group, previously set properties // will not apply to newly added group if (hasSetSTPALL_) userWarnings_.push_back("Make sure to call setSTP on group "+grpName); if (hasSetSTDPALL_) userWarnings_.push_back("Make sure to call setSTDP on group "+grpName); if (hasSetHomeoALL_) userWarnings_.push_back("Make sure to call setHomeostasis on group "+grpName); if (hasSetHomeoBaseFiringALL_) userWarnings_.push_back("Make sure to call setHomeoBaseFiringRate on group "+grpName); int grpId = snn_->createGroup(grpName.c_str(), grid, neurType, preferredPartition, preferredBackend); grpIds_.push_back(grpId); // keep track of all groups int partitionOffset = 0; if (preferredBackend == CPU_CORES) partitionOffset = MAX_NUM_CUDA_DEVICES; else if (preferredBackend == GPU_CORES) partitionOffset = 0; int prefPartition = preferredPartition + partitionOffset; groupPrefNetIds_.insert(std::pair<int, int>(grpId, prefPartition)); // extend 2D connection matrices to number of groups connSyn_.resize(grpIds_.size()); connComp_.resize(grpIds_.size()); return grpId; } // create a group of LIF spiking neurons on 3D grid int createGroupLIF(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { std::string funcName = "createGroupLIF(\""+grpName+"\")"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(grid.numX>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numX"); UserErrors::assertTrue(grid.numY>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numY"); UserErrors::assertTrue(grid.numZ>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numZ"); // if user has called any set functions with grpId=ALL, and is now adding another group, previously set properties // will not apply to newly added group if (hasSetSTPALL_) userWarnings_.push_back("Make sure to call setSTP on group "+grpName); if (hasSetSTDPALL_) userWarnings_.push_back("Make sure to call setSTDP on group "+grpName); if (hasSetHomeoALL_) userWarnings_.push_back("Make sure to call setHomeostasis on group "+grpName); if (hasSetHomeoBaseFiringALL_) userWarnings_.push_back("Make sure to call setHomeoBaseFiringRate on group "+grpName); int grpId = snn_->createGroupLIF(grpName.c_str(), grid, neurType, preferredPartition, preferredBackend); grpIds_.push_back(grpId); // keep track of all groups int partitionOffset = 0; if (preferredBackend == CPU_CORES) partitionOffset = MAX_NUM_CUDA_DEVICES; else if (preferredBackend == GPU_CORES) partitionOffset = 0; int prefPartition = preferredPartition + partitionOffset; groupPrefNetIds_.insert(std::pair<int, int>(grpId, prefPartition)); // extend 2D connection matrices to number of groups connSyn_.resize(grpIds_.size()); connComp_.resize(grpIds_.size()); return grpId; } // create group of spike generators on 1D grid int createSpikeGeneratorGroup(const std::string& grpName, int nNeur, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return createSpikeGeneratorGroup(grpName, Grid3D(nNeur,1,1), neurType, preferredPartition, preferredBackend); } // create group of spike generators on 3D grid int createSpikeGeneratorGroup(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { std::string funcName = "createSpikeGeneratorGroup(\""+grpName+"\")"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(grid.numX>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numX"); UserErrors::assertTrue(grid.numY>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numY"); UserErrors::assertTrue(grid.numZ>0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grid.numZ"); int grpId = snn_->createSpikeGeneratorGroup(grpName.c_str(),grid,neurType, preferredPartition, preferredBackend); grpIds_.push_back(grpId); // keep track of all groups // extend 2D connection matrices to number of groups connSyn_.resize(grpIds_.size()); connComp_.resize(grpIds_.size()); return grpId; } void setCompartmentParameters(int grpId, float couplingUp, float couplingDown) { std::string funcName = "setCompartmentParameters(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->setCompartmentParameters(grpId, couplingUp, couplingDown); } #define LN_I_CALC_TYPES__REQUIRED_FOR_NETWORK_LEVEL // set conductance values, use defaults void setConductances(bool isSet) { std::stringstream funcName; funcName << "setConductances(" << isSet << ")"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use default values snn_->setConductances(true, def_tdAMPA_, 0, def_tdNMDA_, def_tdGABAa_, 0, def_tdGABAb_); } else { // disable conductances snn_->setConductances(false, 0, 0, 0, 0, 0, 0); } } // set conductances values, CUSTOM void setConductances(bool isSet, int tdAMPA, int tdNMDA, int tdGABAa, int tdGABAb) { std::stringstream funcName; funcName << "setConductances(" << isSet << "," << tdAMPA << "," << tdNMDA << "," << tdGABAa << "," << tdGABAb << ")"; UserErrors::assertTrue(!isSet || tdAMPA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdAMPA"); UserErrors::assertTrue(!isSet || tdNMDA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdNMDA"); UserErrors::assertTrue(!isSet || tdGABAa > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAa"); UserErrors::assertTrue(!isSet || tdGABAb > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use custom values snn_->setConductances(true, tdAMPA, 0, tdNMDA, tdGABAa, 0, tdGABAb); } else { // disable conductances snn_->setConductances(false, 0, 0, 0, 0, 0, 0); } } // set conductances values, custom void setConductances(bool isSet, int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { std::stringstream funcName; funcName << "setConductances(" << isSet << "," << tdAMPA << "," << trNMDA << "," << tdNMDA << "," << tdGABAa << "," << trGABAb << "," << tdGABAb << ")"; UserErrors::assertTrue(!isSet || tdAMPA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdAMPA"); UserErrors::assertTrue(!isSet || trNMDA >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trNMDA"); UserErrors::assertTrue(!isSet || tdNMDA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdNMDA"); UserErrors::assertTrue(!isSet || tdGABAa > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAa"); UserErrors::assertTrue(!isSet || trGABAb >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(!isSet || tdGABAb > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(trNMDA != tdNMDA, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trNMDA and tdNMDA"); UserErrors::assertTrue(trGABAb != tdGABAb, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trGABAb and tdGABAb"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use custom values snn_->setConductances(true, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } else { // disable conductances snn_->setConductances(false, 0, 0, 0, 0, 0, 0); } } #ifdef LN_I_CALC_TYPES // LN2021 // set conductance values, use defaults void setConductances(int grpId, bool isSet) { std::stringstream funcName; funcName << "setConductances(" << grpId << "," << isSet << ")"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use default values snn_->setConductances(grpId, true, def_tdAMPA_, 0, def_tdNMDA_, def_tdGABAa_, 0, def_tdGABAb_); } else { // disable conductances snn_->setConductances(grpId, false, 0, 0, 0, 0, 0, 0); } } // set conductances values, CUSTOM void setConductances(int grpId, bool isSet, int tdAMPA, int tdNMDA, int tdGABAa, int tdGABAb) { std::stringstream funcName; funcName << "setConductances(" << grpId << "," << isSet << "," << tdAMPA << "," << tdNMDA << "," << tdGABAa << "," << tdGABAb << ")"; UserErrors::assertTrue(!isSet || tdAMPA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdAMPA"); UserErrors::assertTrue(!isSet || tdNMDA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdNMDA"); UserErrors::assertTrue(!isSet || tdGABAa > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAa"); UserErrors::assertTrue(!isSet || tdGABAb > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use custom values snn_->setConductances(grpId, true, tdAMPA, 0, tdNMDA, tdGABAa, 0, tdGABAb); } else { // disable conductances snn_->setConductances(grpId, false, 0, 0, 0, 0, 0, 0); } } // set conductances values, custom void setConductances(int grpId, bool isSet, int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { std::stringstream funcName; funcName << "setConductances(" << grpId << "," << isSet << "," << tdAMPA << "," << trNMDA << "," << tdNMDA << "," << tdGABAa << "," << trGABAb << "," << tdGABAb << ")"; UserErrors::assertTrue(!isSet || tdAMPA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdAMPA"); UserErrors::assertTrue(!isSet || trNMDA >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trNMDA"); UserErrors::assertTrue(!isSet || tdNMDA > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdNMDA"); UserErrors::assertTrue(!isSet || tdGABAa > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAa"); UserErrors::assertTrue(!isSet || trGABAb >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(!isSet || tdGABAb > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(trNMDA != tdNMDA, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trNMDA and tdNMDA"); UserErrors::assertTrue(trGABAb != tdGABAb, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trGABAb and tdGABAb"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; if (isSet) { // enable conductances, use custom values snn_->setConductances(grpId, true, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } else { // disable conductances snn_->setConductances(grpId, false, 0, 0, 0, 0, 0, 0); } } #endif #ifdef LN_I_CALC_TYPES void setACNE12(int grpId) { //_snn->setACNE12(grpId); // TODO LN2021 } void setNM4weighted(int grpId, IcalcType icalc, float wDA, float w5HT, float wACh, float wNE, float wNorm, float wBase) { std::stringstream funcName; funcName << "setNM4weighted(" << grpId << "," << icalc << "," << wDA << "," << w5HT << "," << wACh << "," << wNE << "," << wNorm << "," << wBase << ")"; // TODO ln // UserErrors::assertTrue(wNorm > 0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "wNorm"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "CONFIG."); hasSetConductances_ = true; // API check if(icalc == alpha1_ADK13) // set Conductance defaults snn_->setConductances(grpId, true, def_tdAMPA_, 0, def_tdNMDA_, def_tdGABAa_, 0, def_tdGABAb_); snn_->setNM4weighted(grpId, icalc, wDA, w5HT, wACh, wNE, wNorm, wBase); } #endif // set default homeostasis params void setHomeostasis(int grpId, bool isSet) { std::string funcName = "setHomeostasis(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetHomeoALL_ = grpId==ALL; // adding groups after this will not have homeostasis set if (isSet) { // enable homeostasis, use default values snn_->setHomeostasis(grpId,true,def_homeo_scale_,def_homeo_avgTimeScale_); if (grpId!=ALL && hasSetHomeoBaseFiringALL_) userWarnings_.push_back("Make sure to call setHomeoBaseFiringRate on group " + getGroupName(grpId)); } else { // disable conductances snn_->setHomeostasis(grpId,false,0.0f,0.0f); } } // set custom homeostasis params for group void setHomeostasis(int grpId, bool isSet, float homeoScale, float avgTimeScale) { std::string funcName = "setHomeostasis(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetHomeoALL_ = grpId==ALL; // adding groups after this will not have homeostasis set if (isSet) { // enable homeostasis, use default values snn_->setHomeostasis(grpId,true,homeoScale,avgTimeScale); if (grpId!=ALL && hasSetHomeoBaseFiringALL_) userWarnings_.push_back("Make sure to call setHomeoBaseFiringRate on group " + getGroupName(grpId)); } else { // disable conductances snn_->setHomeostasis(grpId,false,0.0f,0.0f); } } // set a homeostatic target firing rate (enforced through homeostatic synaptic scaling) void setHomeoBaseFiringRate(int grpId, float baseFiring, float baseFiringSD) { std::string funcName = "setHomeoBaseFiringRate(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(isGroupWithHomeostasis(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName, " Must call setHomeostasis first."); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetHomeoBaseFiringALL_ = grpId==ALL; // adding groups after this will not have base firing set snn_->setHomeoBaseFiringRate(grpId, baseFiring, baseFiringSD); } // sets integration method (FORWARD_EULER, RUNGE_KUTTA4, etc.) and integration step void setIntegrationMethod(integrationMethod_t method, int numStepsPerMs) { std::string funcName = "setIntegrationMethod()"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue((numStepsPerMs >= 1) && (numStepsPerMs <= 100), UserErrors::MUST_BE_IN_RANGE, funcName, "numStepsPerMs", "[1, 100]"); snn_->setIntegrationMethod(method, numStepsPerMs); //std::cout << "numStepsPerMs is (in interface): " + numStepsPerMs << std::endl; } // set neuron parameters for Izhikevich neuron, with standard deviations void setNeuronParameters(int grpId, float izh_a, float izh_a_sd, float izh_b, float izh_b_sd, float izh_c, float izh_c_sd, float izh_d, float izh_d_sd) { std::string funcName = "setNeuronParameters(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); // wrapper identical to core func snn_->setNeuronParameters(grpId, izh_a, izh_a_sd, izh_b, izh_b_sd, izh_c, izh_c_sd, izh_d, izh_d_sd); } // set neuron parameters for Izhikevich neuron void setNeuronParameters(int grpId, float izh_a, float izh_b, float izh_c, float izh_d) { std::string funcName = "setNeuronParameters(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); // set standard deviations of Izzy params to zero snn_->setNeuronParameters(grpId, izh_a, 0.0f, izh_b, 0.0f, izh_c, 0.0f, izh_d, 0.0f); } void setNeuronParameters(int grpId, float izh_C, float izh_k, float izh_vr, float izh_vt, float izh_a, float izh_b, float izh_vpeak, float izh_c, float izh_d) { std::string funcName = "setNeuronParameters(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(izh_C > 0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "izh_C"); // set standard deviations of Izzy params to zero snn_->setNeuronParameters(grpId, izh_C, 0.0f, izh_k, 0.0f, izh_vr, 0.0f, izh_vt, 0.0f, izh_a, 0.0f, izh_b, 0.0f, izh_vpeak, 0.0f, izh_c, 0.0f, izh_d, 0.0f); } void setNeuronParameters(int grpId, float izh_C, float izh_C_sd, float izh_k, float izh_k_sd, float izh_vr, float izh_vr_sd, float izh_vt, float izh_vt_sd, float izh_a, float izh_a_sd, float izh_b, float izh_b_sd, float izh_vpeak, float izh_vpeak_sd, float izh_c, float izh_c_sd, float izh_d, float izh_d_sd) { std::string funcName = "setNeuronParameters(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(izh_C > 0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "izh_C"); // wrapper identical to core func snn_->setNeuronParameters(grpId, izh_C, izh_C_sd, izh_k, izh_k_sd, izh_vr, izh_vr_sd, izh_vt, izh_vt_sd, izh_a, izh_a_sd, izh_b, izh_b_sd, izh_vpeak, izh_vpeak_sd, izh_c, izh_c_sd, izh_d, izh_d_sd); } // set neuron parameters for LIF spiking neuron void setNeuronParametersLIF(int grpId, int tau_m, int tau_ref, float vTh, float vReset, const RangeRmem& rMem) { std::string funcName = "setNeuronParametersLIF(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(tau_m >= 0 , UserErrors::CANNOT_BE_NEGATIVE, funcName, "tau_m"); UserErrors::assertTrue(tau_ref >= 0 , UserErrors::CANNOT_BE_NEGATIVE, funcName, "tau_ref"); UserErrors::assertTrue(vReset < vTh , UserErrors::CANNOT_BE_LARGER, funcName, "vReset"); UserErrors::assertTrue(rMem.minRmem >= 0.0f , UserErrors::CANNOT_BE_NEGATIVE, funcName, "rangeRmem.minRmem"); UserErrors::assertTrue(rMem.minRmem <= rMem.maxRmem , UserErrors::CANNOT_BE_LARGER, funcName, "rangeRmem.minRmem"); // wrapper identical to core func snn_->setNeuronParametersLIF(grpId, tau_m, tau_ref, vTh, vReset,rMem.minRmem, rMem.maxRmem); } // set parameters for each neuronmodulator void setNeuromodulator(int grpId, float baseDP, float tauDP, float releaseDP, bool activeDP, float base5HT, float tau5HT, float release5HT, bool active5HT, float baseACh, float tauACh, float releaseACh, bool activeACh, float baseNE, float tauNE, float releaseNE, bool activeNE) { std::string funcName = "setNeuromodulator(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(baseDP >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName); // LN2021: due to decay UserErrors::assertTrue(tauDP > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(base5HT >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName); UserErrors::assertTrue(tau5HT > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(baseACh >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName); UserErrors::assertTrue(tauACh > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(baseNE >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName); UserErrors::assertTrue(tauNE > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->setNeuromodulator(grpId, baseDP, tauDP, releaseDP, activeDP, base5HT, tau5HT, release5HT, active5HT, baseACh, tauACh, releaseACh, activeACh, baseNE, tauNE, releaseNE, activeNE); } // set parameters for each neuronmodulator void setNeuromodulator(int grpId, float baseDP, float tauDP, float base5HT, float tau5HT, float baseACh, float tauACh, float baseNE, float tauNE) { std::string funcName = "setNeuromodulator(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(baseDP > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tauDP > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(base5HT > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tau5HT > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(baseACh > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tauACh > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(baseNE > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tauNE > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->setNeuromodulator(grpId, baseDP, tauDP, base5HT, tau5HT, baseACh, tauACh, baseNE, tauNE); } void setNeuromodulator(int grpId,float tauDP, float tau5HT, float tauACh, float tauNE) { std::string funcName = "setNeuromodulator(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(tauDP > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tau5HT > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tauACh > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(tauNE > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->setNeuromodulator(grpId, 1.0f, tauDP, 1.0f, tau5HT, 1.0f, tauACh, 1.0f, tauNE); } // set STDP, default, wrapper function void setSTDP(int preGrpId, int postGrpId, bool isSet) { setESTDP(preGrpId, postGrpId, isSet); } // set STDP, custom, wrapper function void setSTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, float alphaPlus, float tauPlus, float alphaMinus, float tauMinus) { setESTDP(preGrpId, postGrpId, isSet, type, ExpCurve(alphaPlus, tauPlus, alphaMinus, tauMinus)); } // set ESTDP, default void setESTDP(int preGrpId, int postGrpId, bool isSet) { std::string funcName = "setESTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use default values and type snn_->setESTDP(preGrpId, postGrpId, true, def_STDP_type_, EXP_CURVE, def_STDP_alphaLTP_, def_STDP_tauLTP_, def_STDP_alphaLTD_, def_STDP_tauLTD_, 0.0f); } else { // disable STDP snn_->setESTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); } } // set ESTDP by stdp curve void setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve) { std::string funcName = "setESTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(type!=UNKNOWN_STDP, UserErrors::CANNOT_BE_UNKNOWN, funcName, "Mode"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use custom values snn_->setESTDP(preGrpId, postGrpId, true, type, curve.stdpCurve, curve.alphaPlus, curve.tauPlus, curve.alphaMinus, curve.tauMinus, 0.0f); } else { // disable STDP and DA-STDP as well snn_->setESTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); } } #ifdef LN_I_CALC_TYPES // set ESTDP by stdp curve void setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve, PkaPlcModulation modulation) { std::string funcName = "setESTDP(\"" + getGroupName(preGrpId) + ", " + getGroupName(postGrpId) + "\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(type == modulation.type, UserErrors::MUST_BE_IN_RANGE, funcName, "Mode"); UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId == ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use custom values snn_->setESTDP(preGrpId, postGrpId, true, type, curve.stdpCurve, curve.alphaPlus, curve.tauPlus, curve.alphaMinus, curve.tauMinus, modulation.nm_pka(), modulation.w_pka(), modulation.nm_plc(), modulation.w_plc() ); } else { // disable STDP and DA-STDP as well snn_->setESTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); } } // set connection nm void setConnectionModulation(int preGrpId, int postGrpId, IcalcType icalcType) { snn_->setConnectionModulation(preGrpId, postGrpId, icalcType); } #endif // set ESTDP by stdp curve void setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, TimingBasedCurve curve) { std::string funcName = "setESTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(type!=UNKNOWN_STDP, UserErrors::CANNOT_BE_UNKNOWN, funcName, "Mode"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use custom values snn_->setESTDP(preGrpId, postGrpId, true, type, curve.stdpCurve, curve.alphaPlus, curve.tauPlus, curve.alphaMinus, curve.tauMinus, curve.gamma); } else { // disable STDP and DA-STDP as well snn_->setESTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f); } } // set ISTDP, default void setISTDP(int preGrpId, int postGrpId, bool isSet) { std::string funcName = "setISTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use default values and types snn_->setISTDP(preGrpId, postGrpId, true, def_STDP_type_, PULSE_CURVE, def_STDP_betaLTP_, def_STDP_betaLTD_, def_STDP_lambda_, def_STDP_delta_); } else { // disable STDP snn_->setISTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 0.0f, 1.0f, 1.0f); } } // set ISTDP by stdp curve void setISTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve) { std::string funcName = "setISTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(type!=UNKNOWN_STDP, UserErrors::CANNOT_BE_UNKNOWN, funcName, "Mode"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use custom values snn_->setISTDP(preGrpId, postGrpId, true, type, curve.stdpCurve, curve.alphaPlus, curve.alphaMinus, curve.tauPlus, curve.tauMinus); } else { // disable STDP and DA-STDP as well snn_->setISTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 0.0f, 1.0f, 1.0f); } } // set ISTDP by stdp curve void setISTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, PulseCurve curve) { std::string funcName = "setISTDP(\""+getGroupName(preGrpId) + ", " + getGroupName(postGrpId) +"\")"; UserErrors::assertTrue(!isSet || isSet && !isPoissonGroup(postGrpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(type!=UNKNOWN_STDP, UserErrors::CANNOT_BE_UNKNOWN, funcName, "Mode"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTDPALL_ = postGrpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use custom values snn_->setISTDP(preGrpId, postGrpId, true, type, curve.stdpCurve, curve.betaLTP, curve.betaLTD, curve.lambda, curve.delta); } else { // disable STDP and DA-STDP as well snn_->setISTDP(preGrpId, postGrpId, false, UNKNOWN_STDP, UNKNOWN_CURVE, 0.0f, 0.0f, 1.0f, 1.0f); } } // set STP, default void setSTP(int grpId, bool isSet) { std::string funcName = "setSTP(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTPALL_ = grpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use default values UserErrors::assertTrue(isExcitatoryGroup(grpId) || isInhibitoryGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, "setSTP"); if (isExcitatoryGroup(grpId)) snn_->setSTP(grpId,true,def_STP_U_exc_,def_STP_tau_u_exc_,def_STP_tau_x_exc_); else if (isInhibitoryGroup(grpId)) snn_->setSTP(grpId,true,def_STP_U_inh_,def_STP_tau_u_inh_,def_STP_tau_x_inh_); else { // some error message } } else { // disable STDP snn_->setSTP(grpId,false,0.0f,0.0f,0.0f); } } // set STP, custom void setSTP(int grpId, bool isSet, float STP_U, float STP_tau_u, float STP_tau_x) { std::string funcName = "setSTP(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); hasSetSTPALL_ = grpId==ALL; // adding groups after this will not have conductances set if (isSet) { // enable STDP, use default values UserErrors::assertTrue(isExcitatoryGroup(grpId) || isInhibitoryGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName,"setSTP"); snn_->setSTP(grpId,true,STP_U,STP_tau_u,STP_tau_x); } else { // disable STDP snn_->setSTP(grpId,false,0.0f,0.0f,0.0f); } } #ifdef LN_I_CALC_TYPES // set neuromodulator targeting STP void setNM4STP(int grpId, float wSTP_U[], float wSTP_tau_u[], float wSTP_tau_x[]) { std::string funcName = "setNM4STP(\"" + getGroupName(grpId) + "\")"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); //// \todo check wp in config group map // snn_->groupConfigMap[gGrpId].stpConfig.WithSTP // --> // snn_->isGroupWithSTP(grpId); //if (isSet) { // UserErrors::assertTrue(isExcitatoryGroup(grpId) || isInhibitoryGroup(grpId), UserErrors::WRONG_NEURON_TYPE, // funcName, "setSTP"); //} snn_->setNM4STP(grpId, wSTP_U, wSTP_tau_u, wSTP_tau_x); } #endif void setWeightAndWeightChangeUpdate(UpdateInterval wtANDwtChangeUpdateInterval, bool enableWtChangeDecay, float wtChangeDecay) { std::string funcName = "setWeightAndWeightChangeUpdate()"; UserErrors::assertTrue(wtChangeDecay > 0.0f, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(wtChangeDecay < 1.0f, UserErrors::CANNOT_BE_LARGER, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->setWeightAndWeightChangeUpdate(wtANDwtChangeUpdateInterval, enableWtChangeDecay, wtChangeDecay); } // +++++++++ PUBLIC METHODS: RUNNING A SIMULATION +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // run network with custom options int runNetwork(int nSec, int nMsec, bool printRunSummary) { std::string funcName = "runNetwork()"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); // run some checks before running network for the first time if (carlsimState_ != RUN_STATE) { // if user hasn't called setConductances, set to false and disp warning if (!hasSetConductances_) { userWarnings_.push_back("setConductances has not been called. Setting simulation mode to CUBA."); } // make sure user didn't provoque any user warnings handleUserWarnings(); } carlsimState_ = RUN_STATE; return snn_->runNetwork(nSec, nMsec, printRunSummary); } // setup network with custom options void setupNetwork() { std::string funcName = "setupNetwork()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); carlsimState_ = SETUP_STATE; snn_->setupNetwork(); } #ifdef LN_SETUP_NETWORK_MT // setup network with custom options void setupNetworkMT() { std::string funcName = "setupNetworkMT()"; UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); carlsimState_ = SETUP_STATE; snn_->setupNetworkMT(); } #endif // +++++++++ PUBLIC METHODS: LOGGING / PLOTTING +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // const FILE* getLogFpInf() { return snn_->getLogFpInf(); } const FILE* getLogFpErr() { return snn_->getLogFpErr(); } const FILE* getLogFpDeb() { return snn_->getLogFpDeb(); } const FILE* getLogFpLog() { return snn_->getLogFpLog(); } void saveSimulation(const std::string& fileName, bool saveSynapseInfo) { FILE* fpSave = fopen(fileName.c_str(),"wb"); std::string funcName = "saveSimulation()"; UserErrors::assertTrue(fpSave!=NULL,UserErrors::FILE_CANNOT_OPEN,fileName); UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); snn_->saveSimulation(fpSave,saveSynapseInfo); fclose(fpSave); } void setLogFile(const std::string& fileName) { std::string funcName = "setLogFile("+fileName+")"; UserErrors::assertTrue(loggerMode_!=CUSTOM,UserErrors::CANNOT_BE_SET_TO, funcName, "Logger mode", "CUSTOM"); FILE* fpLog = NULL; std::string fileNameNonConst = fileName; std::transform(fileNameNonConst.begin(), fileNameNonConst.end(), fileNameNonConst.begin(), ::tolower); if (fileNameNonConst=="null") { #if defined(WIN32) || defined(WIN64) fpLog = fopen("nul","w"); #else fpLog = fopen("/dev/null","w"); #endif } else { fpLog = fopen(fileName.c_str(),"w"); } UserErrors::assertTrue(fpLog!=NULL, UserErrors::FILE_CANNOT_OPEN, funcName, fileName); // change only CARLsim log file pointer (use NULL as code for leaving the others unchanged) snn_->setLogsFp(NULL, NULL, NULL, fpLog); } // set new file pointer for all files in CUSTOM mode void setLogsFpCustom(FILE* fpInf, FILE* fpErr, FILE* fpDeb, FILE* fpLog) { UserErrors::assertTrue(loggerMode_==CUSTOM,UserErrors::MUST_BE_SET_TO,"setLogsFpCustom","Logger mode","CUSTOM"); snn_->setLogsFp(fpInf,fpErr,fpDeb,fpLog); } // +++++++++ PUBLIC METHODS: INTERACTING WITH A SIMULATION ++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // adds a constant bias to the weight of every synapse in the connection void biasWeights(short int connId, float bias, bool updateWeightRange) { std::stringstream funcName; funcName << "biasWeights(" << connId << "," << bias << "," << updateWeightRange << ")"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections()]"); snn_->biasWeights(connId, bias, updateWeightRange); } void startTesting(bool updateWeights) { std::string funcName = "startTesting()"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); snn_->startTesting(updateWeights); } void stopTesting() { std::string funcName = "stopTesting()"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); snn_->stopTesting(); } // reads network state from file void loadSimulation(FILE* fid) { std::string funcName = "loadSimulation()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); snn_->loadSimulation(fid); } // scales the weight of every synapse in the connection with a scaling factor void scaleWeights(short int connId, float scale, bool updateWeightRange) { std::stringstream funcName; funcName << "scaleWeights(" << connId << "," << scale << "," << updateWeightRange << ")"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections()]"); UserErrors::assertTrue(scale>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "Scaling factor"); snn_->scaleWeights(connId, scale, updateWeightRange); } // set spike monitor for group and write spikes to file ConnectionMonitor* setConnectionMonitor(int grpIdPre, int grpIdPost, const std::string& fname) { std::string funcName = "setConnectionMonitor(\"" + getGroupName(grpIdPre) + "\",\"" + getGroupName(grpIdPost) + "\",\"" + fname + "\")"; UserErrors::assertTrue(grpIdPre!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpIdPre"); UserErrors::assertTrue(grpIdPost!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpIdPost"); UserErrors::assertTrue(grpIdPre>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grpIdPre"); UserErrors::assertTrue(grpIdPost>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grpIdPost"); UserErrors::assertTrue(carlsimState_==SETUP_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP."); FILE* fid; std::string fileName = fname; std::transform(fileName.begin(), fileName.end(), fileName.begin(), ::tolower); if (fileName == "null") { // user does not want a binary file created fid = NULL; } else { // try to open spike file if (fileName == "default") { fileName = "results/conn_" + snn_->getGroupName(grpIdPre) + "_" + snn_->getGroupName(grpIdPost) + ".dat"; } else { fileName = fname; } fid = fopen(fileName.c_str(),"wb"); if (fid == NULL) { // file could not be opened // default case: print error and exit std::string fileError = " Double-check file permissions and make sure directory exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError); } } // return ConnectionMonitor object return snn_->setConnectionMonitor(grpIdPre, grpIdPost, fid); } void setExternalCurrent(int grpId, const std::vector<float>& current) { std::string funcName = "setExternalCurrent(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(current.size()==getGroupNumNeurons(grpId), UserErrors::MUST_BE_IDENTICAL, funcName, "current.size()", "number of neurons in the group."); UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); snn_->setExternalCurrent(grpId, current); } void setExternalCurrent(int grpId, float current) { std::string funcName = "setExternalCurrent(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(!isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); std::vector<float> vecCurrent(getGroupNumNeurons(grpId), current); snn_->setExternalCurrent(grpId, vecCurrent); } // set group monitor for a group GroupMonitor* setGroupMonitor(int grpId, const std::string& fname, const int mode) { std::string funcName = "setGroupMonitor(\""+getGroupName(grpId)+"\",\""+fname+"\")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); // grpId can't be ALL UserErrors::assertTrue(grpId>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grpId"); // grpId can't be negative UserErrors::assertTrue(carlsimState_==CONFIG_STATE || carlsimState_==SETUP_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG or SETUP."); FILE* fid; std::string fileName = fname; std::transform(fileName.begin(), fileName.end(), fileName.begin(), ::tolower); if (fileName == "null") { // user does not want a binary file created fid = NULL; } else { // try to open spike file if (fileName == "default") { fileName = "results/grp_" + snn_->getGroupName(grpId) + ".dat"; } else { fileName = fname; } fid = fopen(fileName.c_str(),"wb"); if (fid == NULL) { // file could not be opened // default case: print error and exit std::string fileError = " Double-check file permissions and make sure directory exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError); } } // return GroupMonitor object return snn_->setGroupMonitor(grpId, fid, mode); } // sets up a spike generator void setSpikeGenerator(int grpId, SpikeGenerator* spikeGenFunc) { std::string funcName = "setSpikeGenerator(\""+getGroupName(grpId)+"\")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); // groupId can't be ALL UserErrors::assertTrue(isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(spikeGenFunc!=NULL, UserErrors::CANNOT_BE_NULL, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); // SpikeGeneratorCore* SGC = new SpikeGeneratorCore(this, spikeGenFunc); SpikeGeneratorCore* SGC = new SpikeGeneratorCore(sim_, spikeGenFunc); spkGen_.push_back(SGC); snn_->setSpikeGenerator(grpId, SGC); } // set spike monitor for group and write spikes to file SpikeMonitor* setSpikeMonitor(int grpId, const std::string& fileName) { std::string funcName = "setSpikeMonitor(\""+getGroupName(grpId)+"\",\""+fileName+"\")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); // grpId can't be ALL UserErrors::assertTrue(grpId>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grpId"); // grpId can't be negative UserErrors::assertTrue(carlsimState_==CONFIG_STATE || carlsimState_==SETUP_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG or SETUP."); FILE* fid; std::string fileNameLower = fileName; std::transform(fileNameLower.begin(), fileNameLower.end(), fileNameLower.begin(), ::tolower); if (fileNameLower == "null") { // user does not want a binary file created fid = NULL; } else { // try to open spike file if (fileNameLower == "default") { std::string fileNameDefault = "results/spk_" + snn_->getGroupName(grpId) + ".dat"; fid = fopen(fileNameDefault.c_str(),"wb"); if (fid==NULL) { std::string fileError = " Make sure results/ exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileNameDefault, fileError); } } else { fid = fopen(fileName.c_str(),"wb"); if (fid==NULL) { std::string fileError = " Double-check file permissions and make sure directory exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError); } } } // return SpikeMonitor object return snn_->setSpikeMonitor(grpId, fid); } // set neuron monitor for group and write neuron state values (voltage, recovery, and total current values) to file NeuronMonitor* setNeuronMonitor(int grpId, const std::string& fileName) { std::string funcName = "setNeuronMonitor(\"" + getGroupName(grpId) + "\",\"" + fileName + "\")"; UserErrors::assertTrue(grpId != ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); // grpId can't be ALL UserErrors::assertTrue(grpId >= 0, UserErrors::CANNOT_BE_NEGATIVE, funcName, "grpId"); // grpId can't be negative UserErrors::assertTrue(carlsimState_ == CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); FILE* fid; std::string fileNameLower = fileName; std::transform(fileNameLower.begin(), fileNameLower.end(), fileNameLower.begin(), ::tolower); if (fileNameLower == "null") { // user does not want a binary file created fid = NULL; } else { // try to open spike file if (fileNameLower == "default") { std::string fileNameDefault = "results/n_" + snn_->getGroupName(grpId) + ".dat"; fid = fopen(fileNameDefault.c_str(), "wb"); if (fid == NULL) { std::string fileError = " Make sure results/ exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileNameDefault, fileError); } } else { fid = fopen(fileName.c_str(), "wb"); if (fid == NULL) { std::string fileError = " Double-check file permissions and make sure directory exists."; UserErrors::assertTrue(false, UserErrors::FILE_CANNOT_OPEN, funcName, fileName, fileError); } } } // return NeuronMonitor object return snn_->setNeuronMonitor(grpId, fid); } // assign spike rate to poisson group void setSpikeRate(int grpId, PoissonRate* spikeRate, int refPeriod) { std::string funcName = "setSpikeRate()"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); UserErrors::assertTrue(isPoissonGroup(grpId), UserErrors::WRONG_NEURON_TYPE, funcName, funcName); UserErrors::assertTrue(spikeRate->getNumNeurons()==getGroupNumNeurons(grpId), UserErrors::MUST_BE_IDENTICAL, funcName, "PoissonRate length and the number of neurons in the group"); // FIXME: make sure spikeRate->isOnGPU() consistent with simulation mode //UserErrors::assertTrue(!spikeRate->isOnGPU() || spikeRate->isOnGPU()&&getSimMode()==GPU_MODE, // UserErrors::CAN_ONLY_BE_CALLED_IN_MODE, funcName, "PoissonRate on GPU", "GPU_MODE."); snn_->setSpikeRate(grpId, spikeRate, refPeriod); } void setWeight(short int connId, int neurIdPre, int neurIdPost, float weight, bool updateWeightRange) { std::stringstream funcName; funcName << "setWeight(" << connId << "," << neurIdPre << "," << neurIdPost << "," << updateWeightRange << ")"; UserErrors::assertTrue(carlsimState_==SETUP_STATE || carlsimState_==RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connectionId", "[0,getNumConnections()]"); UserErrors::assertTrue(weight>=0.0f, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "Weight value"); snn_->setWeight(connId, neurIdPre, neurIdPost, weight, updateWeightRange); } // +++++++++ PUBLIC METHODS: SETTERS / GETTERS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // CARLsimState getCARLsimState() { return carlsimState_; } #ifdef LN_GET_FIRING // write store instead of get void getFiring(std::vector<bool>& firings, int netId) { snn_->updateCurSpike(firings, netId); } #endif #ifdef LN_GET_FIRING_MT // write store instead of get void getFiringMT(std::vector<bool>& firings, int netId) { snn_->updateCurSpikeMT(firings, netId); } #endif std::vector<float> getConductanceAMPA(int grpId) { std::string funcName = "getConductanceAMPA()"; UserErrors::assertTrue(carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "RUN."); UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "grpId", "[0,getNumGroups()]"); return snn_->getConductanceAMPA(grpId); } std::vector<float> getConductanceNMDA(int grpId) { std::string funcName = "getConductanceNMDA()"; UserErrors::assertTrue(carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "RUN."); UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "grpId", "[0,getNumGroups()]"); return snn_->getConductanceNMDA(grpId); } std::vector<float> getConductanceGABAa(int grpId) { std::string funcName = "getConductanceGABAa()"; UserErrors::assertTrue(carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "RUN."); UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "grpId", "[0,getNumGroups()]"); return snn_->getConductanceGABAa(grpId); } std::vector<float> getConductanceGABAb(int grpId) { std::string funcName = "getConductanceGABAb()"; UserErrors::assertTrue(carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "RUN."); UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName, "grpId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "grpId", "[0,getNumGroups()]"); return snn_->getConductanceGABAb(grpId); } RangeDelay getDelayRange(short int connId) { std::stringstream funcName; funcName << "getDelayRange(" << connId << ")"; UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections()]"); return snn_->getDelayRange(connId); } // \TODO bad API design (return allocated memory space) uint8_t* getDelays(int gIDpre, int gIDpost, int& Npre, int& Npost) { std::string funcName = "getDelays()"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); UserErrors::assertTrue(gIDpre>=0 && gIDpre<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "gIDpre", "[0,getNumGroups()]"); UserErrors::assertTrue(gIDpost>=0 && gIDpost<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName, "gIDpre", "[0,getNumGroups()]"); return snn_->getDelays(gIDpre,gIDpost,Npre,Npost); } Grid3D getGroupGrid3D(int grpId) { std::stringstream funcName; funcName << "getGroupGrid3D(" << grpId << ")"; UserErrors::assertTrue(grpId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName.str(), "grpId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getGroupGrid3D(grpId); } int getGroupId(std::string grpName) { return snn_->getGroupId(grpName); } std::string getGroupName(int grpId) { std::stringstream funcName; funcName << "getGroupName(" << grpId << ")"; UserErrors::assertTrue(grpId==ALL || grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()] or must be ALL."); return snn_->getGroupName(grpId); } int getGroupStartNeuronId(int grpId) { std::stringstream funcName; funcName << "getGroupStartNeuronId(" << grpId << ")"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getGroupStartNeuronId(grpId); } int getGroupEndNeuronId(int grpId) { std::stringstream funcName; funcName << "getGroupEndNeuronId(" << grpId << ")"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getGroupEndNeuronId(grpId); } int getGroupNumNeurons(int grpId) { std::stringstream funcName; funcName << "getGroupNumNeurons(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getGroupNumNeurons(grpId); } Point3D getNeuronLocation3D(int neurId) { std::stringstream funcName; funcName << "getNeuronLocation3D(" << neurId << ")"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(neurId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName.str(), "neurId"); UserErrors::assertTrue(neurId>=0 && neurId<getNumNeurons(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "neurId", "[0,getNumNeurons()]"); return snn_->getNeuronLocation3D(neurId); } Point3D getNeuronLocation3D(int grpId, int relNeurId) { std::stringstream funcName; funcName << "getNeuronLocation3D(" << grpId << "," << relNeurId << ")"; UserErrors::assertTrue(relNeurId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName.str(), "neurId"); UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); UserErrors::assertTrue(relNeurId>=0 && relNeurId<getGroupNumNeurons(grpId), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "relNeurId", "[0,getGroupNumNeurons()]"); return snn_->getNeuronLocation3D(grpId, relNeurId); } int getNeuronId (int grpId, Point3D location) { std::stringstream funcName; funcName << "getNeuronId(" << grpId << "," << location << ")"; // UserErrors::assertTrue(relNeurId != ALL, UserErrors::ALL_NOT_ALLOWED, funcName.str(), "neurId"); UserErrors::assertTrue(grpId >= 0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); // UserErrors::assertTrue(relNeurId >= 0 && relNeurId<getGroupNumNeurons(grpId), UserErrors::MUST_BE_IN_RANGE, // funcName.str(), "relNeurId", "[0,getGroupNumNeurons()]"); //TODO LN validate what to do if outsite the grid return snn_->getNeuronId(grpId, location); } int getNumConnections() { return snn_->getNumConnections(); } int getMaxNumCompConnections() { return (int)MAX_NUM_COMP_CONN; } int getNumGroups() { return snn_->getNumGroups(); } int getNumNeurons() { return snn_->getNumNeurons(); } int getNumNeuronsReg() { return snn_->getNumNeuronsReg(); } int getNumNeuronsRegExc() { return snn_->getNumNeuronsRegExc(); } int getNumNeuronsRegInh() { return snn_->getNumNeuronsRegInh(); } int getNumNeuronsGen() { return snn_->getNumNeuronsGen(); } int getNumNeuronsGenExc() { return snn_->getNumNeuronsGenExc(); } int getNumNeuronsGenInh() { return snn_->getNumNeuronsGenInh(); } int getNumSynapticConnections(short int connectionId) { std::stringstream funcName; funcName << "getNumConnections(" << connectionId << ")"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), funcName.str(), "SETUP or RUN."); UserErrors::assertTrue(connectionId!=ALL, UserErrors::ALL_NOT_ALLOWED, funcName.str(), "connectionId"); UserErrors::assertTrue(connectionId>=0 && connectionId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connectionId", "[0,getNumSynapticConnections()]"); return snn_->getNumSynapticConnections(connectionId); } int getNumSynapses() { std::string funcName = "getNumSynapses()"; UserErrors::assertTrue(carlsimState_ == SETUP_STATE || carlsimState_ == RUN_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "SETUP or RUN."); return snn_->getNumSynapses(); } ConnSTDPInfo getConnSTDPInfo(int connId) { std::stringstream funcName; funcName << "getConnSTDPInfo(" << connId << ")"; UserErrors::assertTrue(connId >= 0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections]"); return snn_->getConnSTDPInfo(connId); } GroupNeuromodulatorInfo getGroupNeuromodulatorInfo(int grpId) { std::stringstream funcName; funcName << "getGroupNeuromodulatorInfo(" << grpId << ")"; UserErrors::assertTrue(grpId >= 0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getGroupNeuromodulatorInfo(grpId); } int getSimTime() { return snn_->getSimTime(); } int getSimTimeSec() { return snn_->getSimTimeSec(); } int getSimTimeMsec() { return snn_->getSimTimeMs(); } // returns pointer to existing SpikeMonitor object, NULL else SpikeMonitor* getSpikeMonitor(int grpId) { std::stringstream funcName; funcName << "getSpikeMonitor(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "grpId", "[0,getNumGroups()]"); return snn_->getSpikeMonitor(grpId); } RangeWeight getWeightRange(short int connId) { std::stringstream funcName; funcName << "getWeightRange(" << connId << ")"; UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections()]"); return snn_->getWeightRange(connId); } bool isConnectionPlastic(short int connId) { std::stringstream funcName; funcName << "isConnectionPlastic(" << connId << ")"; UserErrors::assertTrue(connId>=0 && connId<getNumConnections(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumConnections()]"); return snn_->isConnectionPlastic(connId); } bool isGroupWithHomeostasis(int grpId) { std::stringstream funcName; funcName << "isGroupWithHomeostasis(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumGroups()]"); return snn_->isGroupWithHomeostasis(grpId); } bool isSimulationWithCOBA() { std::stringstream funcName; funcName << "isSimulationWithCOBA()"; return snn_->isSimulationWithCOBA(); } bool isSimulationWithCUBA() { std::stringstream funcName; funcName << "isSimulationWithCUBA()"; return snn_->isSimulationWithCUBA(); } #ifdef LN_I_CALC_TYPES bool isGroupWith(int grpId, IcalcType icalcType) { std::stringstream funcName; funcName << "isGroupWith(" << grpId << "," << icalcType << ")"; // \todo name vs desc ? return snn_->isGroupWith(grpId, icalcType); } const IcalcType getIcalcType(int grpId) { std::stringstream funcName; funcName << "getIcalcType(" << grpId << ")"; // \todo name vs desc ? return snn_->getIcalcType(grpId); } bool getConductanceConfig(int grpId, float& dAMPA, float& rNMDA, float& dNMDA, float& dGABAa, float& rGABAb, float& dGABAb) { std::stringstream funcName; funcName << "getConductanceConfig(" << grpId << ")"; if(snn_->isGroupWithCOBA(grpId)) { snn_->getConductanceConfig(grpId, dAMPA, rNMDA, dNMDA, dGABAa, rGABAb, dGABAb); return true; } else return false; } bool getConductanceConfig(int grpId, int& tdAMPA, int& trNMDA, int& tdNMDA, int& tdGABAa, int& trGABAb, int& tdGABAb) { std::stringstream funcName; funcName << "getConductanceConfig(" << grpId << ")"; if (snn_->isGroupWithCOBA(grpId)) { snn_->getConductanceConfig(grpId, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); return true; } else return false; } bool isGroupWithCOBA(int grpId) { std::stringstream funcName; funcName << "isGroupWithCOBA(" << grpId << ")"; return snn_->isGroupWithCOBA(grpId); } bool isGroupWithCUBA(int grpId) { std::stringstream funcName; funcName << "isGroupWithCUBA(" << grpId << ")"; return snn_->isGroupWithCUBA(grpId); } #endif bool isExcitatoryGroup(int grpId) { std::stringstream funcName; funcName << "isExcitatoryGroup(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumGroups()]"); return snn_->isExcitatoryGroup(grpId); } bool isInhibitoryGroup(int grpId) { std::stringstream funcName; funcName << "isInhibitoryGroup(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumGroups()]"); return snn_->isInhibitoryGroup(grpId); } bool isPoissonGroup(int grpId) { std::stringstream funcName; funcName << "isPoissonGroup(" << grpId << ")"; UserErrors::assertTrue(grpId>=0 && grpId<getNumGroups(), UserErrors::MUST_BE_IN_RANGE, funcName.str(), "connId", "[0,getNumGroups()]"); return snn_->isPoissonGroup(grpId); } // +++++++++ PUBLIC METHODS: SET DEFAULTS +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // set default values for conductance decay times void setDefaultConductanceTimeConstants(int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { std::stringstream funcName; funcName << "setDefaultConductanceTimeConstants(" << tdAMPA << "," << trNMDA << "," << tdNMDA << "," << tdGABAa << "," << trGABAb << "," << tdGABAb << ")"; UserErrors::assertTrue(tdAMPA>0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdAMPA"); UserErrors::assertTrue(trNMDA>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trNMDA"); UserErrors::assertTrue(tdNMDA>0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdNMDA"); UserErrors::assertTrue(tdGABAa>0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAa"); UserErrors::assertTrue(trGABAb>=0, UserErrors::CANNOT_BE_NEGATIVE, funcName.str(), "trGABAb"); UserErrors::assertTrue(tdGABAb>0, UserErrors::MUST_BE_POSITIVE, funcName.str(), "tdGABAb"); UserErrors::assertTrue(trNMDA!=tdNMDA, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trNMDA and tdNMDA"); UserErrors::assertTrue(trGABAb!=tdGABAb, UserErrors::CANNOT_BE_IDENTICAL, funcName.str(), "trGABAb and tdGABAb"); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName.str(), "CONFIG."); def_tdAMPA_ = tdAMPA; def_trNMDA_ = trNMDA; def_tdNMDA_ = tdNMDA; def_tdGABAa_ = tdGABAa; def_trGABAb_ = trGABAb; def_tdGABAb_ = tdGABAb; } void setDefaultHomeostasisParams(float homeoScale, float avgTimeScale) { std::string funcName = "setDefaultHomeostasisparams()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); assert(avgTimeScale>0); // TODO make nice def_homeo_scale_ = homeoScale; def_homeo_avgTimeScale_ = avgTimeScale; } void setDefaultSaveOptions(std::string fileName, bool saveSynapseInfo) { std::string funcName = "setDefaultSaveOptions()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); def_save_fileName_ = fileName; def_save_synapseInfo_ = saveSynapseInfo; // try to open save file to make sure we have permission (so the user immediately knows about the error and // doesn't have to wait until their simulation run has ended) FILE* fpTry = fopen(def_save_fileName_.c_str(),"wb"); UserErrors::assertTrue(fpTry!=NULL,UserErrors::FILE_CANNOT_OPEN,"Default save file",def_save_fileName_); fclose(fpTry); } // wrapper function, set default values for E-STDP params void setDefaultSTDPparams(float alphaPlus, float tauPlus, float alphaMinus, float tauMinus, STDPType stdpType) { setDefaultESTDPparams(alphaPlus, tauPlus, alphaMinus, tauMinus, stdpType); } // set default values for E-STDP params void setDefaultESTDPparams(float alphaPlus, float tauPlus, float alphaMinus, float tauMinus, STDPType stdpType) { std::string funcName = "setDefaultESTDPparams()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(tauPlus > 0, UserErrors::MUST_BE_POSITIVE, funcName, "tauPlus"); UserErrors::assertTrue(tauMinus > 0, UserErrors::MUST_BE_POSITIVE, funcName, "tauMinus"); switch(stdpType) { case STANDARD: def_STDP_type_ = STANDARD; break; case DA_MOD: case SE_MOD: case AC_MOD: case NE_MOD: //def_STDP_type_ = DA_MOD; def_STDP_type_ = stdpType; break; default: stdpType=UNKNOWN_STDP; UserErrors::assertTrue(stdpType != UNKNOWN_STDP,UserErrors::CANNOT_BE_UNKNOWN,funcName); break; } def_STDP_alphaLTP_ = alphaPlus; def_STDP_tauLTP_ = tauPlus; def_STDP_alphaLTD_ = alphaMinus; def_STDP_tauLTD_ = tauMinus; } // set default values for I-STDP params void setDefaultISTDPparams(float betaLTP, float betaLTD, float lambda, float delta, STDPType stdpType) { std::string funcName = "setDefaultISTDPparams()"; UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); UserErrors::assertTrue(betaLTP > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(betaLTD > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(lambda > 0, UserErrors::MUST_BE_POSITIVE, funcName); UserErrors::assertTrue(delta > 0, UserErrors::MUST_BE_POSITIVE, funcName); switch(stdpType) { case STANDARD: def_STDP_type_ = STANDARD; break; case DA_MOD: //def_STDP_type_ = DA_MOD; def_STDP_type_ = stdpType; break; default: stdpType=UNKNOWN_STDP; UserErrors::assertTrue(stdpType != UNKNOWN_STDP,UserErrors::CANNOT_BE_UNKNOWN,funcName); break; } def_STDP_betaLTP_ = betaLTP; def_STDP_betaLTD_ = betaLTD; def_STDP_lambda_ = lambda; def_STDP_delta_ = delta; } // set default STP values for an EXCITATORY_NEURON or INHIBITORY_NEURON void setDefaultSTPparams(int neurType, float STP_U, float STP_tau_u, float STP_tau_x) { std::string funcName = "setDefaultSTPparams()"; UserErrors::assertTrue(neurType==EXCITATORY_NEURON || neurType==INHIBITORY_NEURON, UserErrors::WRONG_NEURON_TYPE, funcName); UserErrors::assertTrue(carlsimState_==CONFIG_STATE, UserErrors::CAN_ONLY_BE_CALLED_IN_STATE, funcName, funcName, "CONFIG."); assert(STP_tau_u>0.0f); assert(STP_tau_x>0.0f); switch (neurType) { case EXCITATORY_NEURON: def_STP_U_exc_ = STP_U; def_STP_tau_u_exc_ = STP_tau_u; def_STP_tau_x_exc_ = STP_tau_x; break; case INHIBITORY_NEURON: def_STP_U_inh_ = STP_U; def_STP_tau_u_inh_ = STP_tau_u; def_STP_tau_x_inh_ = STP_tau_x; break; default: // some error message instead of assert UserErrors::assertTrue((neurType == EXCITATORY_NEURON || neurType == INHIBITORY_NEURON),UserErrors::CANNOT_BE_UNKNOWN,funcName); break; } } private: // +++++ PRIVATE METHODS ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // // unsafe computations that would otherwise go in constructor void CARLsimInit() { bool gpuAllocationResult = false; std::string funcName = "CARLsimInit()"; UserErrors::assertTrue(loggerMode_!=UNKNOWN_LOGGER,UserErrors::CANNOT_BE_UNKNOWN,"CARLsim()","Logger mode"); // init SNN object snn_ = new SNN(netName_, preferredSimMode_, loggerMode_, randSeed_); // set default time constants for synaptic current decay // TODO: add ref setDefaultConductanceTimeConstants(5, 0, 150, 6, 0, 150); // set default values for STDP params // \deprecated // \TODO: replace with STDP structs setDefaultESTDPparams(0.001f, 20.0f, -0.0012f, 20.0f, STANDARD); setDefaultISTDPparams(0.001f, 0.0012f, 12.0f, 40.0f, STANDARD); // set default values for STP params // Misha Tsodyks and Si Wu (2013) Short-term synaptic plasticity. Scholarpedia, 8(10):3153., revision #136920 setDefaultSTPparams(EXCITATORY_NEURON, 0.45f, 50.0f, 750.0f); setDefaultSTPparams(INHIBITORY_NEURON, 0.15f, 750.0f, 50.0f); // set default homeostasis params // Ref: Carlson, et al. (2013). Proc. of IJCNN 2013. setDefaultHomeostasisParams(0.1f, 10.0f); // set default save sim params // TODO: when we run executable from local dir, put save file in results/ setDefaultSaveOptions("results/sim_"+netName_+".dat",false); connSyn_.clear(); connComp_.clear(); } // check whether grpId exists in grpIds_ bool existsGrpId(int grpId) { return std::find(grpIds_.begin(), grpIds_.end(), grpId)!=grpIds_.end(); } // print all user warnings, continue only after user input void handleUserWarnings() { if (userWarnings_.size()) { for (int i=0; i<userWarnings_.size(); i++) { CARLSIM_WARN("runNetwork()",userWarnings_[i].c_str()); } fprintf(stdout,"Ignore warnings and continue? Y/n "); char ignoreWarn = std::cin.get(); if (std::cin.fail() || ignoreWarn!='y' && ignoreWarn!='Y') { fprintf(stdout,"Exiting...\n"); exit(1); } } } // +++++ PRIVATE STATIC PROPERTIES ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // static bool gpuAllocation[MAX_NUM_CUDA_DEVICES]; static std::string gpuOccupiedBy[MAX_NUM_CUDA_DEVICES]; #if defined(WIN32) || defined(WIN64) static HANDLE gpuAllocationLock; #else static pthread_mutex_t gpuAllocationLock; #endif // +++++ PRIVATE PROPERTIES +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ // CARLsim* sim_; SNN* snn_; //!< an instance of CARLsim core class std::string netName_; //!< network name int randSeed_; //!< RNG seed LoggerMode loggerMode_; //!< logger mode (USER, DEVELOPER, SILENT, CUSTOM) SimMode preferredSimMode_; //!< preferred simulation mode (CPU_MODE, GPU_MODE, HYBRID_MODE) bool enablePrint_; bool copyState_; //! a 2D matrix storing for each groupId (first dim) to which other groups it is connected to (second dim) std::vector<std::vector<int> > connSyn_; //! a 2D matrix storing for each groupId (first dim) to which other groups it is compartmentally connected //! to (second dim) std::vector<std::vector<int> > connComp_; std::map<int, int> groupPrefNetIds_; //!< a list of all created groups' preferred net ids unsigned int numConnections_; //!< keep track of number of allocated connections std::vector<std::string> userWarnings_; // !< an accumulated list of user warnings std::vector<int> grpIds_; //!< a list of all created group IDs std::vector<SpikeGeneratorCore*> spkGen_; //!< a list of all created spike generators std::vector<ConnectionGeneratorCore*> connGen_; //!< a list of all created connection generators bool hasSetHomeoALL_; //!< informs that homeostasis have been set for ALL groups (can't add more groups) bool hasSetHomeoBaseFiringALL_; //!< informs that base firing has been set for ALL groups (can't add more groups) bool hasSetSTDPALL_; //!< informs that STDP have been set for ALL groups (can't add more groups) bool hasSetSTPALL_; //!< informs that STP have been set for ALL groups (can't add more groups) bool hasSetConductances_; //!< informs that setConductances has been called CARLsimState carlsimState_; //!< the current state of carlsim int def_tdAMPA_; //!< default value for AMPA decay (ms) int def_trNMDA_; //!< default value for NMDA rise (ms) int def_tdNMDA_; //!< default value for NMDA decay (ms) int def_tdGABAa_; //!< default value for GABAa decay (ms) int def_trGABAb_; //!< default value for GABAb rise (ms) int def_tdGABAb_; //!< default value for GABAb decay (ms) // all default values for STDP STDPType def_STDP_type_; //!< default mode for STDP float def_STDP_alphaLTP_; //!< default value for LTP amplitude float def_STDP_tauLTP_; //!< default value for LTP decay (ms) float def_STDP_alphaLTD_; //!< default value for LTD amplitude float def_STDP_tauLTD_; //!< default value for LTD decay (ms) float def_STDP_betaLTP_; //!< default value for LTP amplitude float def_STDP_betaLTD_; //!< default value for LTD amplitude float def_STDP_lambda_; //!< default value for interval of LTP float def_STDP_delta_; //!< default value for interval of LTD // all default values for STP float def_STP_U_exc_; //!< default value for STP U excitatory float def_STP_tau_u_exc_; //!< default value for STP u decay (\tau_F) excitatory (ms) float def_STP_tau_x_exc_; //!< default value for STP x decay (\tau_D) excitatory (ms) float def_STP_U_inh_; //!< default value for STP U inhibitory float def_STP_tau_u_inh_; //!< default value for STP u decay (\tau_F) inhibitory (ms) float def_STP_tau_x_inh_; //!< default value for STP x decay (\tau_D) inhibitory (ms) // all default values for homeostasis float def_homeo_scale_; //!< default homeoScale float def_homeo_avgTimeScale_; //!< default avgTimeScale // all default values for save file std::string def_save_fileName_; //!< file name for saving network info bool def_save_synapseInfo_; //!< flag to inform whether to include synapse info in fpSave_ }; // ****************************************************************************************************************** // // CARLSIM API IMPLEMENTATION // ****************************************************************************************************************** // // initialize static properties bool CARLsim::Impl::gpuAllocation[MAX_NUM_CUDA_DEVICES] = {false}; std::string CARLsim::Impl::gpuOccupiedBy[MAX_NUM_CUDA_DEVICES]; #if defined(WIN32) || defined(WIN64) HANDLE CARLsim::Impl::gpuAllocationLock = CreateMutex(NULL, FALSE, NULL); #else pthread_mutex_t CARLsim::Impl::gpuAllocationLock = PTHREAD_MUTEX_INITIALIZER; #endif // constructor / destructor CARLsim::CARLsim(const std::string& netName, SimMode preferredSimMode, LoggerMode loggerMode, int ithGPUs, int randSeed) : _impl( new Impl(this, netName, preferredSimMode, loggerMode, randSeed) ) {} CARLsim::~CARLsim() { delete _impl; } // connect with primitive type short int CARLsim::connect(int grpId1, int grpId2, const std::string& connType, const RangeWeight& wt, float connProb, const RangeDelay& delay, const RadiusRF& radRF, bool synWtType, float mulSynFast, float mulSynSlow) { return _impl->connect(grpId1, grpId2, connType, wt, connProb, delay, radRF, synWtType, mulSynFast, mulSynSlow); } // connect with custom ConnectionGenerator (short) // TODO: don't need two versions of this... make it (grpId1, grpId2, conn, synWtType, mulSynFast, mulSynSlow) short int CARLsim::connect(int grpId1, int grpId2, ConnectionGenerator* conn, bool synWtType) { return _impl->connect(grpId1, grpId2, conn, synWtType); } short int CARLsim::connect(int grpId1, int grpId2, ConnectionGenerator* conn, float mulSynFast, float mulSynSlow, bool synWtType) { return _impl->connect(grpId1, grpId2, conn, mulSynFast, mulSynSlow, synWtType); } short int CARLsim::connectCompartments(int grpIdLower, int grpIdUpper) { return _impl->connectCompartments(grpIdLower, grpIdUpper); } // create group with / without grid int CARLsim::createGroup(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createGroup(grpName, grid, neurType, preferredPartition, preferredBackend); } int CARLsim::createGroup(const std::string& grpName, int nNeur, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createGroup(grpName, nNeur, neurType, preferredPartition, preferredBackend); } // create LIF group with / without grid int CARLsim::createGroupLIF(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createGroupLIF(grpName, grid, neurType, preferredPartition, preferredBackend); } int CARLsim::createGroupLIF(const std::string& grpName, int nNeur, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createGroupLIF(grpName, nNeur, neurType, preferredPartition, preferredBackend); } // create spike gen group with / without grid int CARLsim::createSpikeGeneratorGroup(const std::string& grpName, const Grid3D& grid, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createSpikeGeneratorGroup(grpName, grid, neurType, preferredPartition, preferredBackend); } int CARLsim::createSpikeGeneratorGroup(const std::string& grpName, int nNeur, int neurType, int preferredPartition, ComputingBackend preferredBackend) { return _impl->createSpikeGeneratorGroup(grpName, nNeur, neurType, preferredPartition, preferredBackend); } void CARLsim::setCompartmentParameters(int grpId, float couplingUp, float couplingDown) { _impl->setCompartmentParameters(grpId, couplingUp, couplingDown); } #define LN_I_CALC_TYPES__REQUIRED_FOR_NETWORK_LEVEL // set conductances void CARLsim::setConductances(bool isSet) { _impl->setConductances(isSet); } void CARLsim::setConductances(bool isSet, int tdAMPA, int tdNMDA, int tdGABAa, int tdGABAb) { _impl->setConductances(isSet, tdAMPA, tdNMDA, tdGABAa, tdGABAb); } void CARLsim::setConductances(bool isSet, int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { _impl->setConductances(isSet, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } #ifdef LN_I_CALC_TYPES // set conductances at group level void CARLsim::setConductances(int grpId, bool isSet) { _impl->setConductances(grpId, isSet); } void CARLsim::setConductances(int grpId, bool isSet, int tdAMPA, int tdNMDA, int tdGABAa, int tdGABAb) { _impl->setConductances(grpId, isSet, tdAMPA, tdNMDA, tdGABAa, tdGABAb); } void CARLsim::setConductances(int grpId, bool isSet, int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { _impl->setConductances(grpId, isSet, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } void CARLsim::setACNE12(int grpId) { _impl->setACNE12(grpId); } void CARLsim::setNM4weighted(int grpId, IcalcType iCalc, float wDA, float w5HT, float wACh, float wNE, float wNorm, float wBase) { _impl->setNM4weighted(grpId, iCalc, wDA, w5HT, wACh, wNE, wNorm, wBase); } #endif // set homeostasis params void CARLsim::setHomeostasis(int grpId, bool isSet, float homeoScale, float avgTimeScale) { _impl->setHomeostasis(grpId, isSet, homeoScale, avgTimeScale); } void CARLsim::setHomeostasis(int grpId, bool isSet) { _impl->setHomeostasis(grpId, isSet); } void CARLsim::setHomeoBaseFiringRate(int grpId, float baseFiring, float baseFiringSD) { _impl->setHomeoBaseFiringRate(grpId, baseFiring, baseFiringSD); } void CARLsim::setIntegrationMethod(integrationMethod_t method, int numStepsPerMs) { _impl->setIntegrationMethod(method, numStepsPerMs); } // set neuron params void CARLsim::setNeuronParameters(int grpId, float izh_a, float izh_a_sd, float izh_b, float izh_b_sd, float izh_c, float izh_c_sd, float izh_d, float izh_d_sd) { _impl->setNeuronParameters(grpId, izh_a, izh_a_sd, izh_b, izh_b_sd, izh_c, izh_c_sd, izh_d, izh_d_sd); } void CARLsim::setNeuronParameters(int grpId, float izh_a, float izh_b, float izh_c, float izh_d) { _impl->setNeuronParameters(grpId, izh_a, izh_b, izh_c, izh_d); } void CARLsim::setNeuronParameters(int grpId, float izh_C, float izh_k, float izh_vr, float izh_vt, float izh_a, float izh_b, float izh_vpeak, float izh_c, float izh_d) { _impl->setNeuronParameters(grpId, izh_C, izh_k, izh_vr, izh_vt, izh_a, izh_b, izh_vpeak, izh_c, izh_d); } void CARLsim::setNeuronParameters(int grpId, float izh_C, float izh_C_sd, float izh_k, float izh_k_sd, float izh_vr, float izh_vr_sd, float izh_vt, float izh_vt_sd, float izh_a, float izh_a_sd, float izh_b, float izh_b_sd, float izh_vpeak, float izh_vpeak_sd, float izh_c, float izh_c_sd, float izh_d, float izh_d_sd) { _impl->setNeuronParameters(grpId, izh_C, izh_C_sd, izh_k, izh_k_sd, izh_vr, izh_vr_sd, izh_vt, izh_vt_sd, izh_a, izh_a_sd, izh_b, izh_b_sd, izh_vpeak, izh_vpeak_sd, izh_c, izh_c_sd, izh_d, izh_d_sd); } void CARLsim::setNeuronParametersLIF(int grpId, int tau_m, int tau_ref, float vTh, float vReset, const RangeRmem& rMem) { _impl->setNeuronParametersLIF(grpId, tau_m, tau_ref, vTh, vReset, rMem); } void CARLsim::setNeuromodulator(int grpId, float baseDP, float tauDP, float releaseDP, bool activeDP, float base5HT, float tau5HT, float release5HT, bool active5HT, float baseACh, float tauACh, float releaseACh, bool activeACh, float baseNE, float tauNE, float releaseNE, bool activeNE) { _impl->setNeuromodulator(grpId, baseDP, tauDP, releaseDP, activeDP, base5HT, tau5HT, release5HT, active5HT, baseACh, tauACh, releaseACh, activeACh, baseNE, tauNE, releaseNE, activeNE); } void CARLsim::setNeuromodulator(int grpId, float baseDP, float tauDP, float base5HT, float tau5HT, float baseACh, float tauACh, float baseNE, float tauNE) { _impl->setNeuromodulator(grpId, baseDP, tauDP, base5HT, tau5HT, baseACh, tauACh, baseNE, tauNE); } // sets default neuromodulators void CARLsim::setNeuromodulator(int grpId, float tauDP, float tau5HT, float tauACh, float tauNE) { _impl->setNeuromodulator(grpId, tauDP, tau5HT, tauACh, tauNE); } // Sets default STDP mode and params void CARLsim::setSTDP(int preGrpId, int postGrpId, bool isSet) { _impl->setSTDP(preGrpId, postGrpId, isSet); } // Sets STDP params for a group, custom void CARLsim::setSTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, float alphaPlus, float tauPlus, float alphaMinus, float tauMinus) { _impl->setSTDP(preGrpId, postGrpId, isSet, type, alphaPlus, tauPlus, alphaMinus, tauMinus); } // Sets default E-STDP mode and parameters void CARLsim::setESTDP(int preGrpId, int postGrpId, bool isSet) { _impl->setESTDP(preGrpId, postGrpId, isSet); } // Sets E-STDP with the exponential curve void CARLsim::setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve) { _impl->setESTDP(preGrpId, postGrpId, isSet, type, curve); } #ifdef LN_I_CALC_TYPES // Sets E-STDP with the exponential curve void CARLsim::setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve, PkaPlcModulation modulation) { _impl->setESTDP(preGrpId, postGrpId, isSet, type, curve, modulation); } void CARLsim::setConnectionModulation(int preGrpId, int postGrpId, IcalcType icalcType) { _impl->setConnectionModulation(preGrpId, postGrpId, icalcType); } #endif // Sets E-STDP with the timing-based curve void CARLsim::setESTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, TimingBasedCurve curve) { _impl->setESTDP(preGrpId, postGrpId, isSet, type, curve); } // Sets default I-STDP mode and parameters void CARLsim::setISTDP(int preGrpId, int postGrpId,bool isSet) { _impl->setESTDP(preGrpId, postGrpId, isSet); } // Sets I-STDP with the exponential curve void CARLsim::setISTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, ExpCurve curve) { _impl->setISTDP(preGrpId, postGrpId, isSet, type, curve); } // Sets I-STDP with the pulse curve void CARLsim::setISTDP(int preGrpId, int postGrpId, bool isSet, STDPType type, PulseCurve curve) { _impl->setISTDP(preGrpId, postGrpId, isSet, type, curve); } // Sets STP params U, tau_u, and tau_x of a neuron group (pre-synaptically) void CARLsim::setSTP(int grpId, bool isSet, float STP_U, float STP_tau_u, float STP_tau_x) { _impl->setSTP(grpId, isSet, STP_U, STP_tau_u, STP_tau_x); } // Sets STP params U, tau_u, and tau_x of a neuron group (pre-synaptically) using default values void CARLsim::setSTP(int grpId, bool isSet) { _impl->setSTP(grpId, isSet); } #ifdef LN_I_CALC_TYPES // Sets neuromodulator targeting STP params U, tau_u, and tau_x of a neuron group (pre-synaptically) void CARLsim::setNM4STP(int grpId, float wSTP_U[], float wSTP_tau_u[], float wSTP_tau_x[]) { _impl->setNM4STP(grpId, wSTP_U, wSTP_tau_u, wSTP_tau_x); } #endif // Sets the weight and weight change update parameters void CARLsim::setWeightAndWeightChangeUpdate(UpdateInterval wtANDwtChangeUpdateInterval, bool enableWtChangeDecay, float wtChangeDecay) { _impl->setWeightAndWeightChangeUpdate(wtANDwtChangeUpdateInterval, enableWtChangeDecay, wtChangeDecay); } // run the simulation for time=(nSec*seconds + nMsec*milliseconds) int CARLsim::runNetwork(int nSec, int nMsec, bool printRunSummary) { return _impl->runNetwork(nSec, nMsec, printRunSummary); } // build the network void CARLsim::setupNetwork() { _impl->setupNetwork(); } #ifdef LN_SETUP_NETWORK_MT // build the network void CARLsim::setupNetworkMT() { _impl->setupNetworkMT(); } #endif const FILE* CARLsim::getLogFpInf() { return _impl->getLogFpInf(); } const FILE* CARLsim::getLogFpErr() { return _impl->getLogFpErr(); } const FILE* CARLsim::getLogFpDeb() { return _impl->getLogFpDeb(); } const FILE* CARLsim::getLogFpLog() { return _impl->getLogFpLog(); } // Saves important simulation and network infos to file. void CARLsim::saveSimulation(const std::string& fileName, bool saveSynapseInfo) { _impl->saveSimulation(fileName, saveSynapseInfo); } // Sets the name of the log file void CARLsim::setLogFile(const std::string& fileName) { _impl->setLogFile(fileName); } // Sets the file pointers for all log files in CUSTOM mode void CARLsim::setLogsFpCustom(FILE* fpInf, FILE* fpErr, FILE* fpDeb, FILE* fpLog) { _impl->setLogsFpCustom(fpInf, fpErr, fpDeb, fpLog); } // Adds a constant bias to the weight of every synapse in the connection void CARLsim::biasWeights(short int connId, float bias, bool updateWeightRange) { _impl->biasWeights(connId, bias, updateWeightRange); } // Loads a simulation (and network state) from file. The file pointer fid must point to a void CARLsim::loadSimulation(FILE* fid) { _impl->loadSimulation(fid); } // Multiplies the weight of every synapse in the connection with a scaling factor void CARLsim::scaleWeights(short int connId, float scale, bool updateWeightRange) { _impl->scaleWeights(connId, scale, updateWeightRange); } // Sets a connection monitor for a group, custom ConnectionMonitor class ConnectionMonitor* CARLsim::setConnectionMonitor(int grpIdPre, int grpIdPost, const std::string& fname) { return _impl->setConnectionMonitor(grpIdPre, grpIdPost, fname); } // Sets the amount of current (mA) to inject into a group void CARLsim::setExternalCurrent(int grpId, const std::vector<float>& current) { _impl->setExternalCurrent(grpId, current); } // Sets the amount of current (mA) to inject to each neuron in a group void CARLsim::setExternalCurrent(int grpId, float current) { _impl->setExternalCurrent(grpId, current); } // Sets a group monitor for a group, custom GroupMonitor class GroupMonitor* CARLsim::setGroupMonitor(int grpId, const std::string& fname, int mode) { return _impl->setGroupMonitor(grpId, fname, mode); } // Associates a SpikeGenerator object with a group void CARLsim::setSpikeGenerator(int grpId, SpikeGenerator* spikeGenFunc) { _impl->setSpikeGenerator(grpId, spikeGenFunc); } // Sets a Spike Monitor for a groups, prints spikes to binary file SpikeMonitor* CARLsim::setSpikeMonitor(int grpId, const std::string& fileName) { return _impl->setSpikeMonitor(grpId, fileName); } // Sets a Neuron Monitor for a groups, prints neuron state values (voltage, recovery, and total current values) to binary file NeuronMonitor* CARLsim::setNeuronMonitor(int grpId, const std::string& fileName) { return _impl->setNeuronMonitor(grpId, fileName); } // Sets a spike rate void CARLsim::setSpikeRate(int grpId, PoissonRate* spikeRate, int refPeriod) { _impl->setSpikeRate(grpId, spikeRate, refPeriod); } // Sets the weight value of a specific synapse void CARLsim::setWeight(short int connId, int neurIdPre, int neurIdPost, float weight, bool updateWeightRange) { _impl->setWeight(connId, neurIdPre, neurIdPost, weight, updateWeightRange); } // Enters a testing phase in which all weight changes are disabled void CARLsim::startTesting(bool updateWeights) { _impl->startTesting(updateWeights); } // Exits a testing phase, making weight changes possible again void CARLsim::stopTesting() { _impl->stopTesting(); } // Returns the current CARLsim state CARLsimState CARLsim::getCARLsimState() { return _impl->getCARLsimState(); } #ifdef LN_GET_FIRING // LN20201101 void CARLsim::getFiring(std::vector<bool>& firing, int netId) { _impl->getFiring(firing, netId); } #endif #ifdef LN_GET_FIRING_MT // LN20201101 void CARLsim::getFiringMT(std::vector<bool>& firing, int netId) { _impl->getFiringMT(firing, netId); } #endif // gets AMPA vector of a group std::vector<float> CARLsim::getConductanceAMPA(int grpId) { return _impl->getConductanceAMPA(grpId); } // gets NMDA vector of a group std::vector<float> CARLsim::getConductanceNMDA(int grpId) { return _impl->getConductanceNMDA(grpId); } // gets GABAa vector of a group std::vector<float> CARLsim::getConductanceGABAa(int grpId) { return _impl->getConductanceGABAa(grpId); } // gets GABAb vector of a group std::vector<float> CARLsim::getConductanceGABAb(int grpId) { return _impl->getConductanceGABAb(grpId); } // returns the RangeDelay struct for a specific connection ID RangeDelay CARLsim::getDelayRange(short int connId) { return _impl->getDelayRange(connId); } // gets delays uint8_t* CARLsim::getDelays(int gIDpre, int gIDpost, int& Npre, int& Npost) { return _impl->getDelays(gIDpre, gIDpost, Npre, Npost); } // returns the 3D grid struct of a group Grid3D CARLsim::getGroupGrid3D(int grpId) { return _impl->getGroupGrid3D(grpId); } int CARLsim::getGroupId(std::string grpName) { return _impl->getGroupId(grpName); } // gets group name std::string CARLsim::getGroupName(int grpId) { return _impl->getGroupName(grpId); } // returns the 3D location a neuron codes for Point3D CARLsim::getNeuronLocation3D(int neurId) { return _impl->getNeuronLocation3D(neurId); } // returns the 3D location a neuron codes for Point3D CARLsim::getNeuronLocation3D(int grpId, int relNeurId) { return _impl->getNeuronLocation3D(grpId, relNeurId); } // int CARLsim::getNeuronId(int grpId, Point3D location) { return _impl->getNeuronId(grpId, location); } // Returns the number of connections (pairs of pre-post groups) in the network int CARLsim::getNumConnections() { return _impl->getNumConnections(); } int CARLsim::getMaxNumCompConnections() { return _impl->getMaxNumCompConnections(); } // returns the number of connections associated with a connection ID int CARLsim::getNumSynapticConnections(short int connectionId) { return _impl->getNumSynapticConnections(connectionId); } // returns the number of groups in the network int CARLsim::getNumGroups() { return _impl->getNumGroups(); } // returns the total number of allocated neurons in the network int CARLsim::getNumNeurons() { return _impl->getNumNeurons(); } // returns the total number of regular (Izhikevich) neurons int CARLsim::getNumNeuronsReg() { return _impl->getNumNeuronsReg(); } // returns the total number of regular (Izhikevich) excitatory neurons int CARLsim::getNumNeuronsRegExc() { return _impl->getNumNeuronsRegExc(); } // returns the total number of regular (Izhikevich) inhibitory neurons int CARLsim::getNumNeuronsRegInh() { return _impl->getNumNeuronsRegInh(); } // returns the total number of spike generator neurons int CARLsim::getNumNeuronsGen() { return _impl->getNumNeuronsGen(); } // returns the total number of excitatory spike generator neurons int CARLsim::getNumNeuronsGenExc() { return _impl->getNumNeuronsGenExc(); } // returns the total number of inhibitory spike generator neurons int CARLsim::getNumNeuronsGenInh() { return _impl->getNumNeuronsGenInh(); } // returns the total number of allocated post-synaptic connections in the network int CARLsim::getNumSynapses() { return _impl->getNumSynapses(); } // returns the first neuron id of a groupd specified by grpId int CARLsim::getGroupStartNeuronId(int grpId) { return _impl->getGroupStartNeuronId(grpId); } // returns the last neuron id of a groupd specified by grpId int CARLsim::getGroupEndNeuronId(int grpId) { return _impl->getGroupEndNeuronId(grpId); } // returns the number of neurons of a group specified by grpId int CARLsim::getGroupNumNeurons(int grpId) { return _impl->getGroupNumNeurons(grpId); } // returns the stdp information of a group specified by grpId ConnSTDPInfo CARLsim::getConnSTDPInfo(int grpId) { return _impl->getConnSTDPInfo(grpId); } // returns the neuromodulator information of a group specified by grpId GroupNeuromodulatorInfo CARLsim::getGroupNeuromodulatorInfo(int grpId) { return _impl->getGroupNeuromodulatorInfo(grpId); } int CARLsim::getSimTime() { return _impl->getSimTime(); } int CARLsim::getSimTimeSec() { return _impl->getSimTimeSec(); } int CARLsim::getSimTimeMsec() { return _impl->getSimTimeMsec(); } // returns pointer to previously allocated SpikeMonitor object, NULL else SpikeMonitor* CARLsim::getSpikeMonitor(int grpId) { return _impl->getSpikeMonitor(grpId); } // returns the RangeWeight struct for a specific connection ID RangeWeight CARLsim::getWeightRange(short int connId) { return _impl->getWeightRange(connId); } // Returns whether a connection is fixed or plastic bool CARLsim::isConnectionPlastic(short int connId) { return _impl->isConnectionPlastic(connId); } // Returns whether a group has homeostasis enabled bool CARLsim::isGroupWithHomeostasis(int grpId) { return _impl->isGroupWithHomeostasis(grpId); } // LN Extensions ICALC \todo define constants bool CARLsim::isSimulationWithCOBA() { return _impl->isSimulationWithCOBA(); } bool CARLsim::isSimulationWithCUBA() { return _impl->isSimulationWithCUBA(); } #ifdef LN_I_CALC_TYPES bool CARLsim::isGroupWith(int grpId, IcalcType icalcType) { return _impl->isGroupWith(grpId, icalcType); } bool CARLsim::isGroupWithCOBA(int grpId) { return _impl->isGroupWithCOBA(grpId); } bool CARLsim::isGroupWithCUBA(int grpId) { return _impl->isGroupWithCUBA(grpId); } IcalcType CARLsim::getIcalcType(int grpId) { return _impl->getIcalcType(grpId); } // returns the conductance paramaters as factor / as float, how they are stored internally bool CARLsim::getConductanceConfig( int grpId, float& dAMPA, float& rNMDA, float& dNMDA, float& dGABAa, float& rGABAb, float& dGABAb) { return _impl->getConductanceConfig(grpId, dAMPA, rNMDA, dNMDA, dGABAa, rGABAb, dGABAb); } // returns the conductance parameters as times in ms (rounded) bool CARLsim::getConductanceConfig(int grpId, int& tdAMPA, int& trNMDA, int& tdNMDA, int& tdGABAa, int& trGABAb, int& tdGABAb) { return _impl->getConductanceConfig(grpId, tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } #endif bool CARLsim::isExcitatoryGroup(int grpId) { return _impl->isExcitatoryGroup(grpId); } bool CARLsim::isInhibitoryGroup(int grpId) { return _impl->isInhibitoryGroup(grpId); } bool CARLsim::isPoissonGroup(int grpId) { return _impl->isPoissonGroup(grpId); } void CARLsim::setDefaultConductanceTimeConstants(int tdAMPA, int trNMDA, int tdNMDA, int tdGABAa, int trGABAb, int tdGABAb) { _impl->setDefaultConductanceTimeConstants(tdAMPA, trNMDA, tdNMDA, tdGABAa, trGABAb, tdGABAb); } // Sets default homeostasis params void CARLsim::setDefaultHomeostasisParams(float homeoScale, float avgTimeScale) { _impl->setDefaultHomeostasisParams(homeoScale, avgTimeScale); } // Sets default options for save file void CARLsim::setDefaultSaveOptions(std::string fileName, bool saveSynapseInfo) { _impl->setDefaultSaveOptions(fileName, saveSynapseInfo); } // sets default STDP params void CARLsim::setDefaultSTDPparams(float alphaPlus, float tauPlus, float alphaMinus, float tauMinus, STDPType stdpType) { _impl->setDefaultSTDPparams(alphaPlus, tauPlus, alphaMinus, tauMinus, stdpType); } // sets default values for E-STDP params void CARLsim::setDefaultESTDPparams(float alphaPlus, float tauPlus, float alphaMinus, float tauMinus, STDPType stdpType) { _impl->setDefaultESTDPparams(alphaPlus, tauPlus, alphaMinus, tauMinus, stdpType); } // sets default values for I-STDP params void CARLsim::setDefaultISTDPparams(float betaLTP, float betaLTD, float lambda, float delta, STDPType stdpType) { _impl->setDefaultISTDPparams(betaLTP, betaLTD, lambda, delta, stdpType); } // Sets default values for STP params U, tau_u, and tau_x of a neuron group (pre-synaptically) void CARLsim::setDefaultSTPparams(int neurType, float STP_U, float STP_tau_u, float STP_tau_x) { _impl->setDefaultSTPparams(neurType, STP_U, STP_tau_u, STP_tau_x); } #ifdef __LN_EXT__ // LN20210227 CAUTION despite included carlsim_conf.h by the consumer, with correct set value // the code is not active when entering by the Visual Studio Debugger from the consumer side. // therefor it is to be considered to pass the DEFINES over cMake ... // UPDATE: defining it in the Project Preprocessor Defines yields the same behavior // furthermore the same seems to apply to _all_ define constants, like __WIN32__ as well. // => When debugging in the external library code loaded Visual Studio, no conclusion about // the code nested in define constants must be made. // however stepping through it shows, if it is acutally active // => s.buids have the the whole source state consistant // => this is a main and essential feature -> tell this D. // Mitigration: loading the conf header containing the external library defines // show the correct values e.g. __LN__EXT__ set. // Conclusion: This has to be considered as a general Visual Studio Bug // or a missing config or a missing feature only available in the enterprise editions // LN Extension 20201017 int CARLsim::cudaDeviceCount() { return SNN::cudaDeviceCount(); } #ifndef __NO_CUDA__ // LN Extension 20201017 void CARLsim::cudaDeviceDescription(unsigned ithGPU, const char** desc) { SNN::cudaDeviceDescription(ithGPU, desc); } #endif #endif
; ; Copyright (c) 2016, Alliance for Open Media. All rights reserved ; ; This source code is subject to the terms of the BSD 2 Clause License and ; the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License ; was not distributed with this source code in the LICENSE file, you can ; obtain it at www.aomedia.org/license/software. If the Alliance for Open ; Media Patent License 1.0 was not distributed with this source code in the ; PATENTS file, you can obtain it at www.aomedia.org/license/patent. ; ; %include "third_party/x86inc/x86inc.asm" SECTION_RODATA pw_64: times 8 dw 64 ; %define USE_PMULHRSW ; NOTE: pmulhrsw has a latency of 5 cycles. Tests showed a performance loss ; when using this instruction. ; ; The add order below (based on ffav1) must be followed to prevent outranges. ; x = k0k1 + k4k5 ; y = k2k3 + k6k7 ; z = signed SAT(x + y) SECTION .text %define LOCAL_VARS_SIZE 16*6 %macro SETUP_LOCAL_VARS 0 ; TODO(slavarnway): using xmm registers for these on ARCH_X86_64 + ; pmaddubsw has a higher latency on some platforms, this might be eased by ; interleaving the instructions. %define k0k1 [rsp + 16*0] %define k2k3 [rsp + 16*1] %define k4k5 [rsp + 16*2] %define k6k7 [rsp + 16*3] packsswb m4, m4 ; TODO(slavarnway): multiple pshufb instructions had a higher latency on ; some platforms. pshuflw m0, m4, 0b ;k0_k1 pshuflw m1, m4, 01010101b ;k2_k3 pshuflw m2, m4, 10101010b ;k4_k5 pshuflw m3, m4, 11111111b ;k6_k7 punpcklqdq m0, m0 punpcklqdq m1, m1 punpcklqdq m2, m2 punpcklqdq m3, m3 mova k0k1, m0 mova k2k3, m1 mova k4k5, m2 mova k6k7, m3 %if ARCH_X86_64 %define krd m12 %define tmp0 [rsp + 16*4] %define tmp1 [rsp + 16*5] mova krd, [GLOBAL(pw_64)] %else %define krd [rsp + 16*4] %if CONFIG_PIC=0 mova m6, [GLOBAL(pw_64)] %else ; build constants without accessing global memory pcmpeqb m6, m6 ;all ones psrlw m6, 15 psllw m6, 6 ;aka pw_64 %endif mova krd, m6 %endif %endm ;------------------------------------------------------------------------------- %if ARCH_X86_64 %define LOCAL_VARS_SIZE_H4 0 %else %define LOCAL_VARS_SIZE_H4 16*4 %endif %macro SUBPIX_HFILTER4 1 cglobal filter_block1d4_%1, 6, 6, 11, LOCAL_VARS_SIZE_H4, \ src, sstride, dst, dstride, height, filter mova m4, [filterq] packsswb m4, m4 %if ARCH_X86_64 %define k0k1k4k5 m8 %define k2k3k6k7 m9 %define krd m10 mova krd, [GLOBAL(pw_64)] pshuflw k0k1k4k5, m4, 0b ;k0_k1 pshufhw k0k1k4k5, k0k1k4k5, 10101010b ;k0_k1_k4_k5 pshuflw k2k3k6k7, m4, 01010101b ;k2_k3 pshufhw k2k3k6k7, k2k3k6k7, 11111111b ;k2_k3_k6_k7 %else %define k0k1k4k5 [rsp + 16*0] %define k2k3k6k7 [rsp + 16*1] %define krd [rsp + 16*2] pshuflw m6, m4, 0b ;k0_k1 pshufhw m6, m6, 10101010b ;k0_k1_k4_k5 pshuflw m7, m4, 01010101b ;k2_k3 pshufhw m7, m7, 11111111b ;k2_k3_k6_k7 %if CONFIG_PIC=0 mova m1, [GLOBAL(pw_64)] %else ; build constants without accessing global memory pcmpeqb m1, m1 ;all ones psrlw m1, 15 psllw m1, 6 ;aka pw_64 %endif mova k0k1k4k5, m6 mova k2k3k6k7, m7 mova krd, m1 %endif dec heightd .loop: ;Do two rows at once movu m4, [srcq - 3] movu m5, [srcq + sstrideq - 3] punpckhbw m1, m4, m4 punpcklbw m4, m4 punpckhbw m3, m5, m5 punpcklbw m5, m5 palignr m0, m1, m4, 1 pmaddubsw m0, k0k1k4k5 palignr m1, m4, 5 pmaddubsw m1, k2k3k6k7 palignr m2, m3, m5, 1 pmaddubsw m2, k0k1k4k5 palignr m3, m5, 5 pmaddubsw m3, k2k3k6k7 punpckhqdq m4, m0, m2 punpcklqdq m0, m2 punpckhqdq m5, m1, m3 punpcklqdq m1, m3 paddsw m0, m4 paddsw m1, m5 %ifidn %1, h8_avg movd m4, [dstq] movd m5, [dstq + dstrideq] %endif paddsw m0, m1 paddsw m0, krd psraw m0, 7 packuswb m0, m0 psrldq m1, m0, 4 %ifidn %1, h8_avg pavgb m0, m4 pavgb m1, m5 %endif movd [dstq], m0 movd [dstq + dstrideq], m1 lea srcq, [srcq + sstrideq ] prefetcht0 [srcq + 4 * sstrideq - 3] lea srcq, [srcq + sstrideq ] lea dstq, [dstq + 2 * dstrideq ] prefetcht0 [srcq + 2 * sstrideq - 3] sub heightd, 2 jg .loop ; Do last row if output_height is odd jne .done movu m4, [srcq - 3] punpckhbw m1, m4, m4 punpcklbw m4, m4 palignr m0, m1, m4, 1 palignr m1, m4, 5 pmaddubsw m0, k0k1k4k5 pmaddubsw m1, k2k3k6k7 psrldq m2, m0, 8 psrldq m3, m1, 8 paddsw m0, m2 paddsw m1, m3 paddsw m0, m1 paddsw m0, krd psraw m0, 7 packuswb m0, m0 %ifidn %1, h8_avg movd m4, [dstq] pavgb m0, m4 %endif movd [dstq], m0 .done: REP_RET %endm ;------------------------------------------------------------------------------- %macro SUBPIX_HFILTER8 1 cglobal filter_block1d8_%1, 6, 6, 14, LOCAL_VARS_SIZE, \ src, sstride, dst, dstride, height, filter mova m4, [filterq] SETUP_LOCAL_VARS dec heightd .loop: ;Do two rows at once movu m0, [srcq - 3] movu m4, [srcq + sstrideq - 3] punpckhbw m1, m0, m0 punpcklbw m0, m0 palignr m5, m1, m0, 13 pmaddubsw m5, k6k7 palignr m2, m1, m0, 5 palignr m3, m1, m0, 9 palignr m1, m0, 1 pmaddubsw m1, k0k1 punpckhbw m6, m4, m4 punpcklbw m4, m4 pmaddubsw m2, k2k3 pmaddubsw m3, k4k5 palignr m7, m6, m4, 13 palignr m0, m6, m4, 5 pmaddubsw m7, k6k7 paddsw m1, m3 paddsw m2, m5 paddsw m1, m2 %ifidn %1, h8_avg movh m2, [dstq] movhps m2, [dstq + dstrideq] %endif palignr m5, m6, m4, 9 palignr m6, m4, 1 pmaddubsw m0, k2k3 pmaddubsw m6, k0k1 paddsw m1, krd pmaddubsw m5, k4k5 psraw m1, 7 paddsw m0, m7 paddsw m6, m5 paddsw m6, m0 paddsw m6, krd psraw m6, 7 packuswb m1, m6 %ifidn %1, h8_avg pavgb m1, m2 %endif movh [dstq], m1 movhps [dstq + dstrideq], m1 lea srcq, [srcq + sstrideq ] prefetcht0 [srcq + 4 * sstrideq - 3] lea srcq, [srcq + sstrideq ] lea dstq, [dstq + 2 * dstrideq ] prefetcht0 [srcq + 2 * sstrideq - 3] sub heightd, 2 jg .loop ; Do last row if output_height is odd jne .done movu m0, [srcq - 3] punpckhbw m3, m0, m0 punpcklbw m0, m0 palignr m1, m3, m0, 1 palignr m2, m3, m0, 5 palignr m4, m3, m0, 13 palignr m3, m0, 9 pmaddubsw m1, k0k1 pmaddubsw m2, k2k3 pmaddubsw m3, k4k5 pmaddubsw m4, k6k7 paddsw m1, m3 paddsw m4, m2 paddsw m1, m4 paddsw m1, krd psraw m1, 7 packuswb m1, m1 %ifidn %1, h8_avg movh m0, [dstq] pavgb m1, m0 %endif movh [dstq], m1 .done: REP_RET %endm ;------------------------------------------------------------------------------- %macro SUBPIX_HFILTER16 1 cglobal filter_block1d16_%1, 6, 6, 14, LOCAL_VARS_SIZE, \ src, sstride, dst, dstride, height, filter mova m4, [filterq] SETUP_LOCAL_VARS .loop: prefetcht0 [srcq + 2 * sstrideq -3] movu m0, [srcq - 3] movu m4, [srcq - 2] pmaddubsw m0, k0k1 pmaddubsw m4, k0k1 movu m1, [srcq - 1] movu m5, [srcq + 0] pmaddubsw m1, k2k3 pmaddubsw m5, k2k3 movu m2, [srcq + 1] movu m6, [srcq + 2] pmaddubsw m2, k4k5 pmaddubsw m6, k4k5 movu m3, [srcq + 3] movu m7, [srcq + 4] pmaddubsw m3, k6k7 pmaddubsw m7, k6k7 paddsw m0, m2 paddsw m1, m3 paddsw m0, m1 paddsw m4, m6 paddsw m5, m7 paddsw m4, m5 paddsw m0, krd paddsw m4, krd psraw m0, 7 psraw m4, 7 packuswb m0, m0 packuswb m4, m4 punpcklbw m0, m4 %ifidn %1, h8_avg pavgb m0, [dstq] %endif lea srcq, [srcq + sstrideq] mova [dstq], m0 lea dstq, [dstq + dstrideq] dec heightd jnz .loop REP_RET %endm INIT_XMM ssse3 SUBPIX_HFILTER16 h8 SUBPIX_HFILTER16 h8_avg SUBPIX_HFILTER8 h8 SUBPIX_HFILTER8 h8_avg SUBPIX_HFILTER4 h8 SUBPIX_HFILTER4 h8_avg ;------------------------------------------------------------------------------- ; TODO(Linfeng): Detect cpu type and choose the code with better performance. %define X86_SUBPIX_VFILTER_PREFER_SLOW_CELERON 1 %if ARCH_X86_64 && X86_SUBPIX_VFILTER_PREFER_SLOW_CELERON %define NUM_GENERAL_REG_USED 9 %else %define NUM_GENERAL_REG_USED 6 %endif %macro SUBPIX_VFILTER 2 cglobal filter_block1d%2_%1, 6, NUM_GENERAL_REG_USED, 15, LOCAL_VARS_SIZE, \ src, sstride, dst, dstride, height, filter mova m4, [filterq] SETUP_LOCAL_VARS %ifidn %2, 8 %define movx movh %else %define movx movd %endif dec heightd %if ARCH_X86 || X86_SUBPIX_VFILTER_PREFER_SLOW_CELERON %if ARCH_X86_64 %define src1q r7 %define sstride6q r8 %define dst_stride dstrideq %else %define src1q filterq %define sstride6q dstrideq %define dst_stride dstridemp %endif mov src1q, srcq add src1q, sstrideq lea sstride6q, [sstrideq + sstrideq * 4] add sstride6q, sstrideq ;pitch * 6 .loop: ;Do two rows at once movx m0, [srcq ] ;A movx m1, [src1q ] ;B punpcklbw m0, m1 ;A B movx m2, [srcq + sstrideq * 2 ] ;C pmaddubsw m0, k0k1 mova m6, m2 movx m3, [src1q + sstrideq * 2] ;D punpcklbw m2, m3 ;C D pmaddubsw m2, k2k3 movx m4, [srcq + sstrideq * 4 ] ;E mova m7, m4 movx m5, [src1q + sstrideq * 4] ;F punpcklbw m4, m5 ;E F pmaddubsw m4, k4k5 punpcklbw m1, m6 ;A B next iter movx m6, [srcq + sstride6q ] ;G punpcklbw m5, m6 ;E F next iter punpcklbw m3, m7 ;C D next iter pmaddubsw m5, k4k5 movx m7, [src1q + sstride6q ] ;H punpcklbw m6, m7 ;G H pmaddubsw m6, k6k7 pmaddubsw m3, k2k3 pmaddubsw m1, k0k1 paddsw m0, m4 paddsw m2, m6 movx m6, [srcq + sstrideq * 8 ] ;H next iter punpcklbw m7, m6 pmaddubsw m7, k6k7 paddsw m0, m2 paddsw m0, krd psraw m0, 7 paddsw m1, m5 packuswb m0, m0 paddsw m3, m7 paddsw m1, m3 paddsw m1, krd psraw m1, 7 lea srcq, [srcq + sstrideq * 2 ] lea src1q, [src1q + sstrideq * 2] packuswb m1, m1 %ifidn %1, v8_avg movx m2, [dstq] pavgb m0, m2 %endif movx [dstq], m0 add dstq, dst_stride %ifidn %1, v8_avg movx m3, [dstq] pavgb m1, m3 %endif movx [dstq], m1 add dstq, dst_stride sub heightd, 2 jg .loop ; Do last row if output_height is odd jne .done movx m0, [srcq ] ;A movx m1, [srcq + sstrideq ] ;B movx m6, [srcq + sstride6q ] ;G punpcklbw m0, m1 ;A B movx m7, [src1q + sstride6q ] ;H pmaddubsw m0, k0k1 movx m2, [srcq + sstrideq * 2 ] ;C punpcklbw m6, m7 ;G H movx m3, [src1q + sstrideq * 2] ;D pmaddubsw m6, k6k7 movx m4, [srcq + sstrideq * 4 ] ;E punpcklbw m2, m3 ;C D movx m5, [src1q + sstrideq * 4] ;F punpcklbw m4, m5 ;E F pmaddubsw m2, k2k3 pmaddubsw m4, k4k5 paddsw m2, m6 paddsw m0, m4 paddsw m0, m2 paddsw m0, krd psraw m0, 7 packuswb m0, m0 %ifidn %1, v8_avg movx m1, [dstq] pavgb m0, m1 %endif movx [dstq], m0 %else ; ARCH_X86_64 movx m0, [srcq ] ;A movx m1, [srcq + sstrideq ] ;B lea srcq, [srcq + sstrideq * 2 ] movx m2, [srcq] ;C movx m3, [srcq + sstrideq] ;D lea srcq, [srcq + sstrideq * 2 ] movx m4, [srcq] ;E movx m5, [srcq + sstrideq] ;F lea srcq, [srcq + sstrideq * 2 ] movx m6, [srcq] ;G punpcklbw m0, m1 ;A B punpcklbw m1, m2 ;A B next iter punpcklbw m2, m3 ;C D punpcklbw m3, m4 ;C D next iter punpcklbw m4, m5 ;E F punpcklbw m5, m6 ;E F next iter .loop: ;Do two rows at once movx m7, [srcq + sstrideq] ;H lea srcq, [srcq + sstrideq * 2 ] movx m14, [srcq] ;H next iter punpcklbw m6, m7 ;G H punpcklbw m7, m14 ;G H next iter pmaddubsw m8, m0, k0k1 pmaddubsw m9, m1, k0k1 mova m0, m2 mova m1, m3 pmaddubsw m10, m2, k2k3 pmaddubsw m11, m3, k2k3 mova m2, m4 mova m3, m5 pmaddubsw m4, k4k5 pmaddubsw m5, k4k5 paddsw m8, m4 paddsw m9, m5 mova m4, m6 mova m5, m7 pmaddubsw m6, k6k7 pmaddubsw m7, k6k7 paddsw m10, m6 paddsw m11, m7 paddsw m8, m10 paddsw m9, m11 mova m6, m14 paddsw m8, krd paddsw m9, krd psraw m8, 7 psraw m9, 7 %ifidn %2, 4 packuswb m8, m8 packuswb m9, m9 %else packuswb m8, m9 %endif %ifidn %1, v8_avg movx m7, [dstq] %ifidn %2, 4 movx m10, [dstq + dstrideq] pavgb m9, m10 %else movhpd m7, [dstq + dstrideq] %endif pavgb m8, m7 %endif movx [dstq], m8 %ifidn %2, 4 movx [dstq + dstrideq], m9 %else movhpd [dstq + dstrideq], m8 %endif lea dstq, [dstq + dstrideq * 2 ] sub heightd, 2 jg .loop ; Do last row if output_height is odd jne .done movx m7, [srcq + sstrideq] ;H punpcklbw m6, m7 ;G H pmaddubsw m0, k0k1 pmaddubsw m2, k2k3 pmaddubsw m4, k4k5 pmaddubsw m6, k6k7 paddsw m0, m4 paddsw m2, m6 paddsw m0, m2 paddsw m0, krd psraw m0, 7 packuswb m0, m0 %ifidn %1, v8_avg movx m1, [dstq] pavgb m0, m1 %endif movx [dstq], m0 %endif ; ARCH_X86_64 .done: REP_RET %endm ;------------------------------------------------------------------------------- %macro SUBPIX_VFILTER16 1 cglobal filter_block1d16_%1, 6, NUM_GENERAL_REG_USED, 16, LOCAL_VARS_SIZE, \ src, sstride, dst, dstride, height, filter mova m4, [filterq] SETUP_LOCAL_VARS %if ARCH_X86 || X86_SUBPIX_VFILTER_PREFER_SLOW_CELERON %if ARCH_X86_64 %define src1q r7 %define sstride6q r8 %define dst_stride dstrideq %else %define src1q filterq %define sstride6q dstrideq %define dst_stride dstridemp %endif lea src1q, [srcq + sstrideq] lea sstride6q, [sstrideq + sstrideq * 4] add sstride6q, sstrideq ;pitch * 6 .loop: movh m0, [srcq ] ;A movh m1, [src1q ] ;B movh m2, [srcq + sstrideq * 2 ] ;C movh m3, [src1q + sstrideq * 2] ;D movh m4, [srcq + sstrideq * 4 ] ;E movh m5, [src1q + sstrideq * 4] ;F punpcklbw m0, m1 ;A B movh m6, [srcq + sstride6q] ;G punpcklbw m2, m3 ;C D movh m7, [src1q + sstride6q] ;H punpcklbw m4, m5 ;E F pmaddubsw m0, k0k1 movh m3, [srcq + 8] ;A pmaddubsw m2, k2k3 punpcklbw m6, m7 ;G H movh m5, [srcq + sstrideq + 8] ;B pmaddubsw m4, k4k5 punpcklbw m3, m5 ;A B movh m7, [srcq + sstrideq * 2 + 8] ;C pmaddubsw m6, k6k7 movh m5, [src1q + sstrideq * 2 + 8] ;D punpcklbw m7, m5 ;C D paddsw m2, m6 pmaddubsw m3, k0k1 movh m1, [srcq + sstrideq * 4 + 8] ;E paddsw m0, m4 pmaddubsw m7, k2k3 movh m6, [src1q + sstrideq * 4 + 8] ;F punpcklbw m1, m6 ;E F paddsw m0, m2 paddsw m0, krd movh m2, [srcq + sstride6q + 8] ;G pmaddubsw m1, k4k5 movh m5, [src1q + sstride6q + 8] ;H psraw m0, 7 punpcklbw m2, m5 ;G H pmaddubsw m2, k6k7 paddsw m7, m2 paddsw m3, m1 paddsw m3, m7 paddsw m3, krd psraw m3, 7 packuswb m0, m3 add srcq, sstrideq add src1q, sstrideq %ifidn %1, v8_avg pavgb m0, [dstq] %endif mova [dstq], m0 add dstq, dst_stride dec heightd jnz .loop REP_RET %else ; ARCH_X86_64 dec heightd movu m1, [srcq ] ;A movu m3, [srcq + sstrideq ] ;B lea srcq, [srcq + sstrideq * 2] punpcklbw m0, m1, m3 ;A B punpckhbw m1, m3 ;A B movu m5, [srcq] ;C punpcklbw m2, m3, m5 ;A B next iter punpckhbw m3, m5 ;A B next iter mova tmp0, m2 ;store to stack mova tmp1, m3 ;store to stack movu m7, [srcq + sstrideq] ;D lea srcq, [srcq + sstrideq * 2] punpcklbw m4, m5, m7 ;C D punpckhbw m5, m7 ;C D movu m9, [srcq] ;E punpcklbw m6, m7, m9 ;C D next iter punpckhbw m7, m9 ;C D next iter movu m11, [srcq + sstrideq] ;F lea srcq, [srcq + sstrideq * 2] punpcklbw m8, m9, m11 ;E F punpckhbw m9, m11 ;E F movu m2, [srcq] ;G punpcklbw m10, m11, m2 ;E F next iter punpckhbw m11, m2 ;E F next iter .loop: ;Do two rows at once pmaddubsw m13, m0, k0k1 mova m0, m4 pmaddubsw m14, m8, k4k5 pmaddubsw m15, m4, k2k3 mova m4, m8 paddsw m13, m14 movu m3, [srcq + sstrideq] ;H lea srcq, [srcq + sstrideq * 2] punpcklbw m14, m2, m3 ;G H mova m8, m14 pmaddubsw m14, k6k7 paddsw m15, m14 paddsw m13, m15 paddsw m13, krd psraw m13, 7 pmaddubsw m14, m1, k0k1 pmaddubsw m1, m9, k4k5 pmaddubsw m15, m5, k2k3 paddsw m14, m1 mova m1, m5 mova m5, m9 punpckhbw m2, m3 ;G H mova m9, m2 pmaddubsw m2, k6k7 paddsw m15, m2 paddsw m14, m15 paddsw m14, krd psraw m14, 7 packuswb m13, m14 %ifidn %1, v8_avg pavgb m13, [dstq] %endif mova [dstq], m13 ; next iter pmaddubsw m15, tmp0, k0k1 pmaddubsw m14, m10, k4k5 pmaddubsw m13, m6, k2k3 paddsw m15, m14 mova tmp0, m6 mova m6, m10 movu m2, [srcq] ;G next iter punpcklbw m14, m3, m2 ;G H next iter mova m10, m14 pmaddubsw m14, k6k7 paddsw m13, m14 paddsw m15, m13 paddsw m15, krd psraw m15, 7 pmaddubsw m14, tmp1, k0k1 mova tmp1, m7 pmaddubsw m13, m7, k2k3 mova m7, m11 pmaddubsw m11, k4k5 paddsw m14, m11 punpckhbw m3, m2 ;G H next iter mova m11, m3 pmaddubsw m3, k6k7 paddsw m13, m3 paddsw m14, m13 paddsw m14, krd psraw m14, 7 packuswb m15, m14 %ifidn %1, v8_avg pavgb m15, [dstq + dstrideq] %endif mova [dstq + dstrideq], m15 lea dstq, [dstq + dstrideq * 2] sub heightd, 2 jg .loop ; Do last row if output_height is odd jne .done movu m3, [srcq + sstrideq] ;H punpcklbw m6, m2, m3 ;G H punpckhbw m2, m3 ;G H pmaddubsw m0, k0k1 pmaddubsw m1, k0k1 pmaddubsw m4, k2k3 pmaddubsw m5, k2k3 pmaddubsw m8, k4k5 pmaddubsw m9, k4k5 pmaddubsw m6, k6k7 pmaddubsw m2, k6k7 paddsw m0, m8 paddsw m1, m9 paddsw m4, m6 paddsw m5, m2 paddsw m0, m4 paddsw m1, m5 paddsw m0, krd paddsw m1, krd psraw m0, 7 psraw m1, 7 packuswb m0, m1 %ifidn %1, v8_avg pavgb m0, [dstq] %endif mova [dstq], m0 .done: REP_RET %endif ; ARCH_X86_64 %endm INIT_XMM ssse3 SUBPIX_VFILTER16 v8 SUBPIX_VFILTER16 v8_avg SUBPIX_VFILTER v8, 8 SUBPIX_VFILTER v8_avg, 8 SUBPIX_VFILTER v8, 4 SUBPIX_VFILTER v8_avg, 4
/** * @file exces/any/manager_intf.hpp * @brief Interface of manager type erasure implementation * * Copyright 2012-2014 Matus Chochlik. Distributed under the Boost * Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef EXCES_ANY_ENTITY_MANAGER_INTF_1403152314_HPP #define EXCES_ANY_ENTITY_MANAGER_INTF_1403152314_HPP #include <exces/any/entity_key.hpp> #include <exces/any/lock.hpp> #include <functional> #include <memory> namespace exces { template <typename Entity> class any_manager; template <typename Entity> struct any_manager_intf { typedef typename any_entity_key::param_type aekp; virtual ~any_manager_intf(void) { } virtual bool has_key(Entity e) = 0; virtual any_entity_key get_key(Entity e) = 0; virtual Entity get_entity(aekp) = 0; virtual bool has(aekp, const char*) = 0; virtual bool has(Entity, const char*) = 0; virtual bool has_all(aekp, const char**) = 0; virtual bool has_some(aekp, const char**) = 0; virtual void reserve(std::size_t, const char**) = 0; virtual void add(aekp, const char**, void**) = 0; virtual void remove(aekp, const char**) = 0; virtual void copy(aekp, aekp, const char**) = 0; virtual any_lock lifetime_lock(const char*) = 0; virtual any_lock raw_access_lock(const char*) = 0; typedef std::vector<std::size_t> entity_update_op; virtual entity_update_op begin_update(aekp) = 0; virtual void finish_update(aekp, const entity_update_op&) = 0; virtual void* raw_access(aekp, const char*) = 0; virtual void for_each_imk( any_manager<Entity>&, const std::function<bool ( const iter_info&, any_manager<Entity>&, const any_entity_key& )>& ) = 0; virtual void for_each_mk( any_manager<Entity>&, const std::function<bool ( any_manager<Entity>&, const any_entity_key& )>& ) = 0; virtual void for_each_c(const void*, const char*) = 0; }; template <typename Group> std::shared_ptr<any_manager_intf<typename entity<Group>::type>> make_any_manager_impl(manager<Group>&); } // namespace exces #endif //include guard
; Listing generated by Microsoft (R) Optimizing Compiler Version 19.00.23506.0 include listing.inc INCLUDELIB MSVCRT INCLUDELIB OLDNAMES PUBLIC __local_stdio_printf_options PUBLIC _vfprintf_l PUBLIC printf PUBLIC func PUBLIC main PUBLIC ??_C@_0BA@NNIFAFEJ@?$CFd?5?$CFd?5?$CFd?5?$CFd?5?$CFs?6?$AA@ ; `string' EXTRN __imp___acrt_iob_func:PROC EXTRN __imp___stdio_common_vfprintf:PROC EXTRN gets:PROC _DATA SEGMENT COMM ?_OptionsStorage@?1??__local_stdio_printf_options@@9@9:QWORD ; `__local_stdio_printf_options'::`2'::_OptionsStorage _DATA ENDS ; COMDAT pdata pdata SEGMENT $pdata$_vfprintf_l DD imagerel $LN4 DD imagerel $LN4+81 DD imagerel $unwind$_vfprintf_l pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$printf DD imagerel $LN4 DD imagerel $LN4+66 DD imagerel $unwind$printf pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$func DD imagerel $LN4 DD imagerel $LN4+95 DD imagerel $unwind$func pdata ENDS ; COMDAT pdata pdata SEGMENT $pdata$main DD imagerel $LN4 DD imagerel $LN4+32 DD imagerel $unwind$main pdata ENDS ; COMDAT ??_C@_0BA@NNIFAFEJ@?$CFd?5?$CFd?5?$CFd?5?$CFd?5?$CFs?6?$AA@ CONST SEGMENT ??_C@_0BA@NNIFAFEJ@?$CFd?5?$CFd?5?$CFd?5?$CFd?5?$CFs?6?$AA@ DB '%d %d %d ' DB '%d %s', 0aH, 00H ; `string' CONST ENDS ; COMDAT xdata xdata SEGMENT $unwind$main DD 010401H DD 04204H xdata ENDS ; COMDAT xdata xdata SEGMENT $unwind$func DD 081401H DD 0c6414H DD 0b5414H DD 0a3414H DD 070107214H xdata ENDS ; COMDAT xdata xdata SEGMENT $unwind$printf DD 021901H DD 030153219H xdata ENDS ; COMDAT xdata xdata SEGMENT $unwind$_vfprintf_l DD 081401H DD 0a6414H DD 095414H DD 083414H DD 070105214H xdata ENDS ; Function compile flags: /Ogtpy ; File d:\projects\taintanalysis\antitaint\epilog\src\func-iparam-fastcall.c ; COMDAT main _TEXT SEGMENT main PROC ; COMDAT ; 23 : { $LN4: sub rsp, 40 ; 00000028H ; 24 : func(1, 2, 3, 4); mov edx, 2 lea r9d, QWORD PTR [rdx+2] lea r8d, QWORD PTR [rdx+1] lea ecx, QWORD PTR [rdx-1] call func ; 25 : return 0; xor eax, eax ; 26 : } add rsp, 40 ; 00000028H ret 0 main ENDP _TEXT ENDS ; Function compile flags: /Ogtpy ; File d:\projects\taintanalysis\antitaint\epilog\src\func-iparam-fastcall.c ; COMDAT func _TEXT SEGMENT buf$ = 48 param1$ = 80 param2$ = 88 param3$ = 96 param4$ = 104 func PROC ; COMDAT ; 16 : { $LN4: mov QWORD PTR [rsp+8], rbx mov QWORD PTR [rsp+16], rbp mov QWORD PTR [rsp+24], rsi push rdi sub rsp, 64 ; 00000040H mov ebp, ecx mov ebx, r9d ; 17 : char buf[8]; ; 18 : gets(buf); lea rcx, QWORD PTR buf$[rsp] mov edi, r8d mov esi, edx call gets ; 19 : printf("%d %d %d %d %s\n", param1, param2, param3, param4, buf); lea rax, QWORD PTR buf$[rsp] mov r9d, edi mov QWORD PTR [rsp+40], rax lea rcx, OFFSET FLAT:??_C@_0BA@NNIFAFEJ@?$CFd?5?$CFd?5?$CFd?5?$CFd?5?$CFs?6?$AA@ mov r8d, esi mov DWORD PTR [rsp+32], ebx mov edx, ebp call printf ; 20 : } mov rbx, QWORD PTR [rsp+80] mov rbp, QWORD PTR [rsp+88] mov rsi, QWORD PTR [rsp+96] add rsp, 64 ; 00000040H pop rdi ret 0 func ENDP _TEXT ENDS ; Function compile flags: /Ogtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h ; COMDAT printf _TEXT SEGMENT _Format$ = 48 printf PROC ; COMDAT ; 950 : { $LN4: mov QWORD PTR [rsp+8], rcx mov QWORD PTR [rsp+16], rdx mov QWORD PTR [rsp+24], r8 mov QWORD PTR [rsp+32], r9 push rbx sub rsp, 32 ; 00000020H ; 951 : int _Result; ; 952 : va_list _ArgList; ; 953 : __crt_va_start(_ArgList, _Format); ; 954 : _Result = _vfprintf_l(stdout, _Format, NULL, _ArgList); mov ecx, 1 lea rbx, QWORD PTR _Format$[rsp+8] call QWORD PTR __imp___acrt_iob_func mov rdx, QWORD PTR _Format$[rsp] mov r9, rbx mov rcx, rax xor r8d, r8d call _vfprintf_l ; 955 : __crt_va_end(_ArgList); ; 956 : return _Result; ; 957 : } add rsp, 32 ; 00000020H pop rbx ret 0 printf ENDP _TEXT ENDS ; Function compile flags: /Ogtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\stdio.h ; COMDAT _vfprintf_l _TEXT SEGMENT _Stream$ = 64 _Format$ = 72 _Locale$ = 80 _ArgList$ = 88 _vfprintf_l PROC ; COMDAT ; 638 : { $LN4: mov QWORD PTR [rsp+8], rbx mov QWORD PTR [rsp+16], rbp mov QWORD PTR [rsp+24], rsi push rdi sub rsp, 48 ; 00000030H mov rbx, r9 mov rdi, r8 mov rsi, rdx mov rbp, rcx ; 639 : return __stdio_common_vfprintf(_CRT_INTERNAL_LOCAL_PRINTF_OPTIONS, _Stream, _Format, _Locale, _ArgList); call __local_stdio_printf_options mov r9, rdi mov QWORD PTR [rsp+32], rbx mov r8, rsi mov rdx, rbp mov rcx, QWORD PTR [rax] call QWORD PTR __imp___stdio_common_vfprintf ; 640 : } mov rbx, QWORD PTR [rsp+64] mov rbp, QWORD PTR [rsp+72] mov rsi, QWORD PTR [rsp+80] add rsp, 48 ; 00000030H pop rdi ret 0 _vfprintf_l ENDP _TEXT ENDS ; Function compile flags: /Ogtpy ; File c:\program files (x86)\windows kits\10\include\10.0.10240.0\ucrt\corecrt_stdio_config.h ; COMDAT __local_stdio_printf_options _TEXT SEGMENT __local_stdio_printf_options PROC ; COMDAT ; 74 : static unsigned __int64 _OptionsStorage; ; 75 : return &_OptionsStorage; lea rax, OFFSET FLAT:?_OptionsStorage@?1??__local_stdio_printf_options@@9@9 ; `__local_stdio_printf_options'::`2'::_OptionsStorage ; 76 : } ret 0 __local_stdio_printf_options ENDP _TEXT ENDS END
; A069459: a(n) = prime(n)^n - 1. ; 1,8,124,2400,161050,4826808,410338672,16983563040,1801152661462,420707233300200,25408476896404830,6582952005840035280,925103102315013629320,73885357344138503765448,12063348350820368238715342,3876269050118516845397872320,1271991467017507741703714391418,136753052840548005895349735207880,49593099428404263766544428188098202 mov $2,$0 seq $0,6005 ; The odd prime numbers together with 1. add $2,1 pow $0,$2 max $0,2 sub $0,1
; =============================================================== ; 2014 ; =============================================================== ; ; void zx_cls(uchar attr) ; ; Clear screen using attibute. ; ; =============================================================== SECTION code_arch PUBLIC asm_zx_cls EXTERN asm_memset asm_zx_cls: ; enter : l = attr ; ; uses : af, bc, de, hl ; attributes ld e,l ld hl,$5800 ld bc,768 call asm_memset ; pixels ld e,0 ld hl,$4000 ld bc,6144 jp asm_memset
_CeruleanHouse1Text1:: text "My husband likes" line "trading #MON." para "If you are a" line "collector, would" cont "you please trade" cont "with him?" done
; /***************************************************************************** ; * ugBASIC - an isomorphic BASIC language compiler for retrocomputers * ; ***************************************************************************** ; * Copyright 2021-2022 Marco Spedaletti (asimov@mclink.it) ; * ; * Licensed under the Apache License, Version 2.0 (the "License"); ; * you may not use this file except in compliance with the License. ; * You may obtain a copy of the License at ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Unless required by applicable law or agreed to in writing, software ; * distributed under the License is distributed on an "AS IS" BASIS, ; * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ; * See the License for the specific language governing permissions and ; * limitations under the License. ; *---------------------------------------------------------------------------- ; * Concesso in licenza secondo i termini della Licenza Apache, versione 2.0 ; * (la "Licenza"); è proibito usare questo file se non in conformità alla ; * Licenza. Una copia della Licenza è disponibile all'indirizzo: ; * ; * http://www.apache.org/licenses/LICENSE-2.0 ; * ; * Se non richiesto dalla legislazione vigente o concordato per iscritto, ; * il software distribuito nei termini della Licenza è distribuito ; * "COSì COM'è", SENZA GARANZIE O CONDIZIONI DI ALCUN TIPO, esplicite o ; * implicite. Consultare la Licenza per il testo specifico che regola le ; * autorizzazioni e le limitazioni previste dalla medesima. ; ****************************************************************************/ ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * ;* * ;* TEXT AT GIVEN POSITION ON TED * ;* * ;* by Marco Spedaletti * ;* * ;* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * TEXTATBITMAPMODE: LDA TEXTADDRESS STA COPYOFTEXTADDRESS LDA TEXTADDRESS+1 STA COPYOFTEXTADDRESS+1 LDA #0 STA TABSTODRAW LDA COLORMAPADDRESS STA COPYOFCOLORMAPADDRESS LDA COLORMAPADDRESS+1 STA COPYOFCOLORMAPADDRESS+1 SEI LDX XCURSYS LDY YCURSYS CLC LDA PLOTVBASELO,Y ;table of $A000 row base addresses ADC PLOT8LO,X ;+ (8 * Xcell) STA PLOTDEST ;= cell address LDA PLOTVBASEHI,Y ;do the high byte ADC PLOT8HI,X STA PLOTDEST+1 CLC TXA ADC PLOTCVBASELO,Y ;table of $8400 row base addresses STA PLOTCDEST ;= cell address LDA #0 ADC PLOTCVBASEHI,Y ;do the high byte STA PLOTCDEST+1 LDX TEXTSIZE LDY #$0 TEXTATBMLOOP2: LDA TABSTODRAW BEQ TEXTATBMNSKIPTAB JMP TEXTATBMSKIPTAB TEXTATBMNSKIPTAB: LDA (TEXTPTR),Y CMP #31 BCS TEXTATBMXCC JMP TEXTATBMCC TEXTATBMXCC: JSR TEXTATDECODE JMP TEXTATBMSP0 TEXTATBMTAB: LDA XCURSYS TEXTATBMTAB2: CMP TABCOUNT BCC TEXTATBMTAB3 SEC SBC TABCOUNT JMP TEXTATBMTAB2 TEXTATBMTAB3: STA TMPPTR LDA TABCOUNT SEC SBC TMPPTR STA TABSTODRAW JMP TEXTATBMNEXT TEXTATBMCC: CMP #13 BEQ TEXTATBMLF CMP #10 BEQ TEXTATBMLF CMP #09 BEQ TEXTATBMTAB CMP #01 BEQ TEXTATBMPEN CMP #02 BEQ TEXTATBMPAPER CMP #03 BEQ TEXTATBMCMOVEPREPARE CMP #04 BEQ TEXTATBMXAT CMP #05 BEQ TEXTATBMCLS JMP TEXTATBMNEXT TEXTATBMCLS: INC TEXTPTR DEX JSR CLSG JMP TEXTATBMNEXT TEXTATBMXAT: JMP TEXTATBMAT TEXTATBMLF: INC TEXTPTR DEX JMP TEXTATBMNEXT2 TEXTATBMPEN: INC TEXTPTR DEX LDA TEXTWW AND #$2 BEQ TEXTATBMPENDISABLED LDA (TEXTPTR), Y ASL A ASL A ASL A ASL A STA _PEN TEXTATBMPENDISABLED: INC TEXTPTR DEY JMP TEXTATBMNEXT TEXTATBMPAPER: INC TEXTPTR DEX LDA TEXTWW AND #$1 BEQ TEXTATBMPAPERDISABLED LDA (TEXTPTR), Y STA _PAPER TEXTATBMPAPERDISABLED: INC TEXTPTR DEY JMP TEXTATBMNEXT TEXTATBMCMOVEPREPARE: INC TEXTPTR DEX LDA (TEXTPTR), Y STA CLINEX INC TEXTPTR DEX LDA (TEXTPTR), Y STA CLINEY TEXTATBMCMOVE: CLC LDA CLINEX ADC XCURSYS STA XCURSYS LDA CLINEY ADC YCURSYS STA YCURSYS JMP TEXTATBMNEXT TEXTATBMAT: INC TEXTPTR DEX LDA (TEXTPTR), Y SEC SBC XCURSYS STA CLINEX INC TEXTPTR DEX LDA (TEXTPTR), Y SEC SBC YCURSYS STA CLINEY JMP TEXTATBMCMOVE TEXTATBMSP0: TYA PHA TXA PHA LDX XCURSYS LDY YCURSYS CLC LDA PLOTVBASELO,Y ;table of $A000 row base addresses ADC PLOT8LO,X ;+ (8 * Xcell) STA PLOTDEST ;= cell address LDA PLOTVBASEHI,Y ;do the high byte ADC PLOT8HI,X STA PLOTDEST+1 CLC TXA ADC PLOTCVBASELO,Y ;table of $8400 row base addresses STA PLOTCDEST ;= cell address LDA #0 ADC PLOTCVBASEHI,Y ;do the high byte STA PLOTCDEST+1 PLA TAX PLA TAY TYA PHA LDY #0 LDA SCREENCODE STA TMPPTR LDA #0 STA TMPPTR+1 CLC ASL TMPPTR ROL TMPPTR+1 CLC ASL TMPPTR ROL TMPPTR+1 CLC ASL TMPPTR ROL TMPPTR+1 CLC LDA #$0 ADC TMPPTR STA TMPPTR LDA #$D0 ADC TMPPTR+1 STA TMPPTR+1 TEXTATBMSP0L1: LDA (TMPPTR),Y STA (PLOTDEST),Y INY CPY #8 BNE TEXTATBMSP0L1 LDA TEXTWW AND #$2 BEQ TEXTATBMCNOPEN LDY #0 LDA (PLOTCDEST),Y ORA _PEN STA (PLOTCDEST),Y TEXTATBMCNOPEN: LDA TEXTWW AND #$1 BEQ TEXTATBMCNOPAPER LDA (PLOTCDEST),Y AND #$f0 ORA _PAPER STA (PLOTCDEST),Y TEXTATBMCNOPAPER: PLA TAY JMP TEXTATBMINCX TEXTATBMSKIPTAB: DEC TABSTODRAW JMP TEXTATBMINCX TEXTATBMINCX: INC XCURSYS LDA XCURSYS CMP #40 BEQ TEXTATBMNEXT2 JMP TEXTATBMNEXT TEXTATBMNEXT2: LDA #0 STA XCURSYS INC YCURSYS LDA YCURSYS CMP #25 BEQ TEXTATBMNEXT3 JMP TEXTATBMNEXT TEXTATBMNEXT3: ; scrolling ? TEXTATBMNEXT: LDA TABSTODRAW BEQ TEXTATBMXLOOP2 JMP TEXTATBMLOOP2 TEXTATBMXLOOP2: INY DEX BEQ TEXTATBMEND JMP TEXTATBMLOOP2 TEXTATBMEND: CLI RTS
; BIOS Parameter Block bpbBytesPerSector: dw 512 ; Bytes per sector bpbSectorsPerCluster: db 1 ; Sectors per cluster bpbReservedSectors: dw 1 ; Number of reserved sectors bpbNumberOfFATs: db 2 ; Number of copies of the file allocation table bpbRootEntries: dw 224 ; Size of root directory bpbTotalSectors: dw 2880 ; Total number of sectors on the disk (if disk less than 32MB) bpbMedia: db 0F0h ; Media descriptor bpbSectorsPerFAT: dw 9 ; Size of file allocation table (in sectors) bpbSectorsPerTrack: dw 18 ; Number of sectors per track bpbHeadsPerCylinder: dw 2 ; Number of read-write heads bpbHiddenSectors: dd 0 ; Number of hidden sectors bpbTotalSectorsBig: dd 0 ; Number of sectors if disk greater than 32MB bsDriveNumber: db 0 ; Drive boot sector came from bsUnused: db 0 ; Reserved bsExtBootSignature: db 29h ; Extended boot sector signature bsSerialNumber: dd 0a0a1a2a3h ; Disk serial number` bsVolumeLabel: db "MOS FLOPP`Y " ; Disk volume label bsFileSystem: db "FAT12 " ; File system type
/******************************************************************** * Copyright (c) 2013 - 2014, Pivotal Inc. * All rights reserved. * * Author: Zhanwei Wang ********************************************************************/ /******************************************************************** * 2014 - * open source under Apache License Version 2.0 ********************************************************************/ /** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "BigEndian.h" #include "DataTransferProtocolSender.h" #include "Exception.h" #include "ExceptionInternal.h" #include "HWCrc32c.h" #include "RemoteBlockReader.h" #include "SWCrc32c.h" #include "WriteBuffer.h" #include <inttypes.h> #include <vector> namespace Hdfs { namespace Internal { RemoteBlockReader::RemoteBlockReader(const ExtendedBlock& eb, DatanodeInfo& datanode, PeerCache& peerCache, int64_t start, int64_t len, const Token& token, const char* clientName, bool verify, SessionConfig& conf) : sentStatus(false), verify(verify), binfo(eb), datanode(datanode), checksumSize(0), chunkSize(0), position(0), size(0), cursor(start), endOffset(len + start), lastSeqNo(-1), peerCache(peerCache) { assert(start >= 0); readTimeout = conf.getInputReadTimeout(); writeTimeout = conf.getInputWriteTimeout(); connTimeout = conf.getInputConnTimeout(); sock = getNextPeer(datanode); in = shared_ptr<BufferedSocketReader>(new BufferedSocketReaderImpl(*sock)); sender = shared_ptr<DataTransferProtocol>(new DataTransferProtocolSender( *sock, writeTimeout, datanode.formatAddress())); sender->readBlock(eb, token, clientName, start, len); checkResponse(); } RemoteBlockReader::~RemoteBlockReader() { if (sentStatus) { peerCache.addConnection(sock, datanode); } else { sock->close(); } } shared_ptr<Socket> RemoteBlockReader::getNextPeer(const DatanodeInfo& dn) { shared_ptr<Socket> sock; try { sock = peerCache.getConnection(dn); if (!sock) { sock = shared_ptr<Socket>(new TcpSocketImpl); sock->connect(dn.getIpAddr().c_str(), dn.getXferPort(), connTimeout); sock->setNoDelay(true); } } catch (const HdfsTimeoutException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: Failed to connect to %s", dn.formatAddress().c_str()); } return sock; } void RemoteBlockReader::checkResponse() { std::vector<char> respBuffer; int32_t respSize = in->readVarint32(readTimeout); if (respSize <= 0 || respSize > 10 * 1024 * 1024) { THROW(HdfsIOException, "RemoteBlockReader get a invalid response size: %d, Block: %s, from Datanode: %s", respSize, binfo.toString().c_str(), datanode.formatAddress().c_str()); } respBuffer.resize(respSize); in->readFully(&respBuffer[0], respSize, readTimeout); BlockOpResponseProto resp; if (!resp.ParseFromArray(&respBuffer[0], respBuffer.size())) { THROW(HdfsIOException, "RemoteBlockReader cannot parse BlockOpResponseProto from Datanode response, " "Block: %s, from Datanode: %s", binfo.toString().c_str(), datanode.formatAddress().c_str()); } if (resp.status() != Status::DT_PROTO_SUCCESS) { std::string msg; if (resp.has_message()) { msg = resp.message(); } if (resp.status() == Status::DT_PROTO_ERROR_ACCESS_TOKEN) { THROW(HdfsInvalidBlockToken, "RemoteBlockReader: block's token is invalid. Datanode: %s, Block: %s", datanode.formatAddress().c_str(), binfo.toString().c_str()); } else { THROW(HdfsIOException, "RemoteBlockReader: Datanode return an error when sending read request to Datanode: %s, Block: %s, %s.", datanode.formatAddress().c_str(), binfo.toString().c_str(), (msg.empty() ? "check Datanode's log for more information" : msg.c_str())); } } const ReadOpChecksumInfoProto & checksumInfo = resp.readopchecksuminfo(); const ChecksumProto & cs = checksumInfo.checksum(); chunkSize = cs.bytesperchecksum(); if (chunkSize < 0) { THROW(HdfsIOException, "RemoteBlockReader invalid chunk size: %d, expected range[0, %" PRId64 "], Block: %s, from Datanode: %s", chunkSize, binfo.getNumBytes(), binfo.toString().c_str(), datanode.formatAddress().c_str()); } switch (cs.type()) { case ChecksumTypeProto::CHECKSUM_NULL: verify = false; checksumSize = 0; break; case ChecksumTypeProto::CHECKSUM_CRC32: // THROW(HdfsIOException, "RemoteBlockReader does not support CRC32 checksum, Block: %s, from Datanode: %s", // binfo.toString().c_str(), datanode.formatAddress().c_str()); checksum = shared_ptr<Checksum>(new Crc32()); checksumSize = sizeof(int32_t); break; case ChecksumTypeProto::CHECKSUM_CRC32C: if (HWCrc32c::available()) { checksum = shared_ptr<Checksum>(new HWCrc32c()); } else { checksum = shared_ptr<Checksum>(new SWCrc32c()); } checksumSize = sizeof(int32_t); break; default: THROW(HdfsIOException, "RemoteBlockReader cannot recognize checksum type: %d, Block: %s, from Datanode: %s", static_cast<int>(cs.type()), binfo.toString().c_str(), datanode.formatAddress().c_str()); } /* * The offset into the block at which the first packet * will start. This is necessary since reads will align * backwards to a checksum chunk boundary. */ int64_t firstChunkOffset = checksumInfo.chunkoffset(); if (firstChunkOffset < 0 || firstChunkOffset > cursor || firstChunkOffset <= cursor - chunkSize) { THROW(HdfsIOException, "RemoteBlockReader invalid first chunk offset: %" PRId64 ", expected range[0, %" PRId64 "], " "Block: %s, from Datanode: %s", firstChunkOffset, cursor, binfo.toString().c_str(), datanode.formatAddress().c_str()); } } shared_ptr<PacketHeader> RemoteBlockReader::readPacketHeader() { try { shared_ptr<PacketHeader> retval; static const int packetHeaderLen = PacketHeader::GetPkgHeaderSize(); std::vector<char> buf(packetHeaderLen); if (lastHeader && lastHeader->isLastPacketInBlock()) { THROW(HdfsIOException, "RemoteBlockReader: read over block end from Datanode: %s, Block: %s.", datanode.formatAddress().c_str(), binfo.toString().c_str()); } in->readFully(&buf[0], packetHeaderLen, readTimeout); retval = shared_ptr<PacketHeader>(new PacketHeader); retval->readFields(&buf[0], packetHeaderLen); return retval; } catch (const HdfsIOException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: failed to read block header for Block: %s from Datanode: %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } } void RemoteBlockReader::readNextPacket() { assert(position >= size); lastHeader = readPacketHeader(); int dataSize = lastHeader->getDataLen(); int64_t pendingAhead = 0; if (!lastHeader->sanityCheck(lastSeqNo)) { THROW(HdfsIOException, "RemoteBlockReader: Packet failed on sanity check for block %s from Datanode %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } assert(dataSize > 0 || lastHeader->getPacketLen() == sizeof(int32_t)); if (dataSize > 0) { int chunks = (dataSize + chunkSize - 1) / chunkSize; int checksumLen = chunks * checksumSize; size = checksumLen + dataSize; assert(size == lastHeader->getPacketLen() - static_cast<int>(sizeof(int32_t))); buffer.resize(size); in->readFully(&buffer[0], size, readTimeout); lastSeqNo = lastHeader->getSeqno(); if (lastHeader->getPacketLen() != static_cast<int>(sizeof(int32_t)) + dataSize + checksumLen) { THROW(HdfsIOException, "Invalid Packet, packetLen is %d, dataSize is %d, checksum size is %d", lastHeader->getPacketLen(), dataSize, checksumLen); } if (verify) { verifyChecksum(chunks); } /* * skip checksum */ position = checksumLen; /* * the first packet we get may start at the position before we required */ pendingAhead = cursor - lastHeader->getOffsetInBlock(); pendingAhead = pendingAhead > 0 ? pendingAhead : 0; position += pendingAhead; } /* * we reach the end of the range we required, send status to datanode * if datanode do not sending data anymore. */ if (cursor + dataSize - pendingAhead >= endOffset && readTrailingEmptyPacket()) { sendStatus(); } } bool RemoteBlockReader::readTrailingEmptyPacket() { shared_ptr<PacketHeader> trailingHeader = readPacketHeader(); if (!trailingHeader->isLastPacketInBlock() || trailingHeader->getDataLen() != 0) { return false; } return true; } void RemoteBlockReader::sendStatus() { ClientReadStatusProto status; if (verify) { status.set_status(Status::DT_PROTO_CHECKSUM_OK); } else { status.set_status(Status::DT_PROTO_SUCCESS); } WriteBuffer buffer; int size = status.ByteSize(); buffer.writeVarint32(size); status.SerializeToArray(buffer.alloc(size), size); sock->writeFully(buffer.getBuffer(0), buffer.getDataSize(0), writeTimeout); sentStatus = true; } void RemoteBlockReader::verifyChecksum(int chunks) { int dataSize = lastHeader->getDataLen(); char * pchecksum = &buffer[0]; char * pdata = &buffer[0] + (chunks * checksumSize); for (int i = 0; i < chunks; ++i) { int size = chunkSize < dataSize ? chunkSize : dataSize; dataSize -= size; checksum->reset(); checksum->update(pdata + (i * chunkSize), size); uint32_t result = checksum->getValue(); uint32_t target = ReadBigEndian32FromArray(pchecksum + (i * checksumSize)); if (result != target && size == chunkSize) { THROW(ChecksumException, "RemoteBlockReader: checksum not match for Block: %s, on Datanode: %s", binfo.toString().c_str(), datanode.formatAddress().c_str()); } } assert(0 == dataSize); } int64_t RemoteBlockReader::available() { return size - position > 0 ? size - position : 0; } int32_t RemoteBlockReader::read(char * buf, int32_t len) { assert(0 != len && NULL != buf); if (cursor >= endOffset) { THROW(HdfsIOException, "RemoteBlockReader: read over block end from Datanode: %s, Block: %s.", datanode.formatAddress().c_str(), binfo.toString().c_str()); } try { if (position >= size) { readNextPacket(); } int32_t todo = len < size - position ? len : size - position; memcpy(buf, &buffer[position], todo); position += todo; cursor += todo; return todo; } catch (const HdfsTimeoutException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: failed to read Block: %s from Datanode: %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } catch (const HdfsNetworkException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: failed to read Block: %s from Datanode: %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } } void RemoteBlockReader::skip(int64_t len) { int64_t todo = len; assert(cursor + len <= endOffset); try { while (todo > 0) { if (cursor >= endOffset) { THROW(HdfsIOException, "RemoteBlockReader: skip over block end from Datanode: %s, Block: %s.", datanode.formatAddress().c_str(), binfo.toString().c_str()); } if (position >= size) { readNextPacket(); } int batch = size - position; batch = batch < todo ? batch : static_cast<int>(todo); position += batch; cursor += batch; todo -= batch; } } catch (const HdfsTimeoutException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: failed to read Block: %s from Datanode: %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } catch (const HdfsNetworkException & e) { NESTED_THROW(HdfsIOException, "RemoteBlockReader: failed to read Block: %s from Datanode: %s.", binfo.toString().c_str(), datanode.formatAddress().c_str()); } } } }
/**************************************************************************** * * Copyright (c) 2020 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file ActuatorEffectivenessRotors.hpp * * Actuator effectiveness computed from rotors position and orientation * * @author Julien Lecoeur <julien.lecoeur@gmail.com> */ #pragma once #include "ActuatorEffectiveness.hpp" #include <px4_platform_common/module_params.h> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionInterval.hpp> class ActuatorEffectivenessTilts; using namespace time_literals; class ActuatorEffectivenessRotors : public ModuleParams, public ActuatorEffectiveness { public: enum class AxisConfiguration { Configurable, ///< axis can be configured FixedForward, ///< axis is fixed, pointing forwards (positive X) FixedUpwards, ///< axis is fixed, pointing upwards (negative Z) }; static constexpr int NUM_ROTORS_MAX = 8; struct RotorGeometry { matrix::Vector3f position; matrix::Vector3f axis; float thrust_coef; float moment_ratio; int tilt_index; }; struct Geometry { RotorGeometry rotors[NUM_ROTORS_MAX]; int num_rotors{0}; bool yaw_disabled{false}; }; ActuatorEffectivenessRotors(ModuleParams *parent, AxisConfiguration axis_config = AxisConfiguration::Configurable, bool tilt_support = false); virtual ~ActuatorEffectivenessRotors() = default; void getDesiredAllocationMethod(AllocationMethod allocation_method_out[MAX_NUM_MATRICES]) const override { allocation_method_out[0] = AllocationMethod::SEQUENTIAL_DESATURATION; } void getNormalizeRPY(bool normalize[MAX_NUM_MATRICES]) const override { normalize[0] = true; } static int computeEffectivenessMatrix(const Geometry &geometry, EffectivenessMatrix &effectiveness, int actuator_start_index = 0); bool addActuators(Configuration &configuration); const char *name() const override { return "Multirotor"; } /** * Sets the motor axis from tilt configurations and current tilt control. * @param tilts configured tilt servos * @param tilt_control current tilt control in [-1, 1] (can be NAN) * @return the motors as bitset which are not tiltable */ uint32_t updateAxisFromTilts(const ActuatorEffectivenessTilts &tilts, float tilt_control); const Geometry &geometry() const { return _geometry; } /** * Get the tilted axis {0, 0, -1} rotated by -tilt_angle around y, then * rotated by tilt_direction around z. */ static matrix::Vector3f tiltedAxis(float tilt_angle, float tilt_direction); void enableYawControl(bool enable) { _geometry.yaw_disabled = !enable; } private: void updateParams() override; const AxisConfiguration _axis_config; const bool _tilt_support; ///< if true, tilt servo assignment params are loaded struct ParamHandles { param_t position_x; param_t position_y; param_t position_z; param_t axis_x; param_t axis_y; param_t axis_z; param_t thrust_coef; param_t moment_ratio; param_t tilt_index; }; ParamHandles _param_handles[NUM_ROTORS_MAX]; param_t _count_handle; Geometry _geometry{}; };
; A128919: Numbers simultaneously heptagonal and centered heptagonal. ; Submitted by Christian Krause ; 1,148,21022,2984983,423846571,60183228106,8545594544488,1213414242089197,172296276782121493,24464857888819162816,3473837523935538998386 mov $3,1 lpb $0 sub $0,1 mov $1,$3 mul $1,10 add $2,$1 add $3,$2 lpe pow $3,2 mov $0,$3 div $0,120 mul $0,147 add $0,1
BITS 64 ;TEST_FILE_META_BEGIN ;TEST_TYPE=TEST_F ;TEST_IGNOREFLAGS=FLAG_CF|FLAG_OF|FLAG_PF|FLAG_SF|FLAG_AF ;TEST_FILE_META_END ; BSR32rr mov eax, 0x08000000 ;TEST_BEGIN_RECORDING bsr ebx, eax ;TEST_END_RECORDING
<% from pwnlib.shellcraft.aarch64.linux import syscall %> <%page args="rgid, egid, sgid"/> <%docstring> Invokes the syscall setresgid. See 'man 2 setresgid' for more information. Arguments: rgid(gid_t): rgid egid(gid_t): egid sgid(gid_t): sgid </%docstring> ${syscall('SYS_setresgid', rgid, egid, sgid)}
/* Copyright (c) 2010-2019, Delft University of Technology * All rigths reserved * * This file is part of the Tudat. Redistribution and use in source and * binary forms, with or without modification, are permitted exclusively * under the terms of the Modified BSD license. You should have received * a copy of the license with this file. If not, please or visit: * http://tudat.tudelft.nl/LICENSE. * */ #include <map> #include <vector> #include <boost/make_shared.hpp> #include "tudat/io/parsedDataVectorUtilities.h" namespace tudat { namespace input_output { namespace parsed_data_vector_utilities { //! Filter the data vector for entries containing a given FieldType. ParsedDataVectorPtr filterMapKey( ParsedDataVectorPtr datavector, int nrFields, ...) { // Create a fancy vector (list) of all the fields: // Define argument list variable. va_list argumentList; // Initialize list; point to last defined argument. va_start( argumentList, nrFields ); // Create a new datavector for the filtered data. ParsedDataVectorPtr newDataVector = std::make_shared< ParsedDataVector >( ); // Make a simple list to iterate over from all the FieldType arguments. std::vector< FieldType > checkForFieldTypes; for ( int i = 0; i < nrFields; i++ ) { checkForFieldTypes.push_back( va_arg( argumentList, FieldType ) ); } // Clean up the system stack. va_end( argumentList ); // Go over every dataline in the current datavector. for ( ParsedDataVector::iterator currentDataLine = datavector->begin( ); currentDataLine != datavector->end( ); currentDataLine++ ) { // Flag to indicate that all the FieldTypes from checkForFieldTypes are present in this // line. bool found = true; // Loop over each FieldType to check if it exists. for ( std::vector< FieldType >::iterator currentFieldCheck = checkForFieldTypes.begin( ); currentFieldCheck != checkForFieldTypes.end( ); currentFieldCheck++ ) { // Check if the FieldType is in the current data line. if ( ( *currentDataLine )->find( *currentFieldCheck ) == ( *currentDataLine )->end( ) ) { // If not, mark that not all entries are present, and stop searching for others. found = false; break; } } // If all the fields are present, add the current line to the new (filtered) vector. if ( found ) { newDataVector->push_back( *currentDataLine ); } } // Return the filtered data vector. return newDataVector; } //! Filter the data vector vector for entries containing a given FieldType and a matching //! FieldValue regex. ParsedDataVectorPtr filterMapKeyValue( ParsedDataVectorPtr datavector, int nrFields, ... ) { // Create a fancy vector (list) of all the fields: // Define argument list variable. va_list argumentList; // Initialize list; point to last defined argument. va_start( argumentList, nrFields ); // Create a new data vector for the filtered data. ParsedDataVectorPtr newDataVector = std::make_shared< ParsedDataVector>( ); // Make a simple list to iterate over with the FieldType arguments and respective regex // expressions. std::map< FieldType, boost::regex > checkForFieldTypes; for ( int i = 0; i < nrFields; i++ ) { FieldType type = va_arg( argumentList, FieldType ); boost::regex regex = boost::regex( va_arg( argumentList, char* ) ); checkForFieldTypes.insert( std::pair< FieldType, boost::regex >( type, regex ) ); } // Clean up the system stack. va_end ( argumentList ); // Go over every dataline in the current data vector. for ( ParsedDataVector::iterator currentDataLine = datavector->begin( ); currentDataLine != datavector->end( ); currentDataLine++ ) { // Flag to indicate that all the FieldTypes from checkForFieldTypes are present in this // line. bool found = true; // Loop over each FieldType to check if it exists. for( std::map< FieldType, boost::regex >::iterator currentFieldCheck = checkForFieldTypes.begin( ); currentFieldCheck != checkForFieldTypes.end( ); currentFieldCheck++) { // Check if the FieldType is in the current dataline ParsedDataLineMap::iterator entry = ( *currentDataLine )->find( currentFieldCheck->first ); if ( entry == ( *currentDataLine )->end( ) ) { // If not, mark that not all entry pairs are present, and stop searching for // others. found = false; break; } // Get the field value string. const std::string str = entry->second->getTransformed( ); // Check if the field value regex matches. if ( !boost::regex_search( str.begin( ), str.end( ), currentFieldCheck->second ) ) { // If not, mark this, and stop searching for others. found = false; break; } } // If all the fields are present, add the current line to the new (filtered) vector. if ( found ) { newDataVector->push_back( *currentDataLine ); } } // Return the filtered data vector. return newDataVector; } //! Dump the content of a data map to an ostream. std::ostream& dump( std::ostream& stream, ParsedDataLineMapPtr data, bool showTransformed ) { // Initial character to separate elements. stream << "|"; // Loop over data map. for ( ParsedDataLineMap::iterator element = data->begin( ); element != data->end( ); element++ ) { // If transformed flag is true, dump transformed values. if ( showTransformed ) { stream << element->second->getTransformed( ); } // If not, dump raw values. else { stream << element->second->getRaw( ); } // Final character to separate elements. stream << "\t|"; } stream << "\n"; return stream; } //! Dump the content of a data vector to an ostream (eg std::cout). std::ostream& dump( std::ostream& stream, ParsedDataVectorPtr data, bool showTransformed ) { // Loop over vector. for ( std::size_t i=0; i < data->size( ); i++ ) { // Get data line. ParsedDataLineMapPtr line = data->at( i ); // Call dump function for single line (datamap). dump ( stream, line, showTransformed ); } return stream; } } // namespace parsed_data_vector_utilities } // namespace input_output } // namespace tudat
.global s_prepare_buffers s_prepare_buffers: push %r15 push %r8 push %rax push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_normal_ht+0x1fb0, %rax and $50495, %r8 mov $0x6162636465666768, %rbx movq %rbx, %xmm1 vmovups %ymm1, (%rax) nop nop nop nop nop cmp %r15, %r15 lea addresses_normal_ht+0x199b0, %rsi lea addresses_normal_ht+0xd56, %rdi nop nop add %r8, %r8 mov $123, %rcx rep movsq nop nop xor %r15, %r15 lea addresses_normal_ht+0x155b0, %rbx nop nop sub %rcx, %rcx vmovups (%rbx), %ymm2 vextracti128 $1, %ymm2, %xmm2 vpextrq $0, %xmm2, %r15 sub %r15, %r15 lea addresses_D_ht+0x23f0, %rsi lea addresses_D_ht+0x140b0, %rdi nop nop xor $11740, %rdx mov $45, %rcx rep movsw nop nop and $1213, %r15 lea addresses_normal_ht+0x1e3b0, %rbx nop nop nop nop inc %rsi mov (%rbx), %dx nop nop nop nop nop dec %rcx lea addresses_A_ht+0x1c6b0, %rsi lea addresses_WT_ht+0x3110, %rdi nop nop nop cmp %rax, %rax mov $70, %rcx rep movsb nop nop nop and %rsi, %rsi lea addresses_WT_ht+0x14c70, %rdx nop nop add $40797, %rbx mov (%rdx), %esi nop nop nop nop cmp $60388, %rsi lea addresses_WC_ht+0x1b2b0, %rsi lea addresses_A_ht+0x19920, %rdi cmp $5230, %rbx mov $9, %rcx rep movsw dec %rcx lea addresses_A_ht+0x4e90, %rsi nop xor $43915, %rdx mov (%rsi), %r8 nop nop nop nop nop and %rsi, %rsi pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %rax pop %r8 pop %r15 ret .global s_faulty_load s_faulty_load: push %r10 push %r11 push %r14 push %rbx push %rcx push %rdx push %rsi // Load lea addresses_WC+0x3900, %rbx clflush (%rbx) nop nop nop nop nop and $43999, %rcx movups (%rbx), %xmm3 vpextrq $1, %xmm3, %rsi nop nop add $34514, %rdx // Store lea addresses_US+0x9bb0, %r11 nop nop nop nop add %rdx, %rdx movl $0x51525354, (%r11) nop nop add $39870, %rsi // Load lea addresses_PSE+0xf88, %r10 nop nop nop nop add $14670, %r14 movups (%r10), %xmm1 vpextrq $0, %xmm1, %rsi add %rdx, %rdx // Faulty Load lea addresses_UC+0xe3b0, %rdx nop and $41648, %r10 movups (%rdx), %xmm0 vpextrq $1, %xmm0, %rsi lea oracles, %rbx and $0xff, %rsi shlq $12, %rsi mov (%rbx,%rsi,1), %rsi pop %rsi pop %rdx pop %rcx pop %rbx pop %r14 pop %r11 pop %r10 ret /* <gen_faulty_load> [REF] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 32, 'AVXalign': False, 'NT': True, 'congruent': 0, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} {'OP': 'STOR', 'dst': {'type': 'addresses_US', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_PSE', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 3, 'same': False}} [Faulty Load] {'OP': 'LOAD', 'src': {'type': 'addresses_UC', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 10, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 9, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 1, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 32, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 4, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 8, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_normal_ht', 'size': 2, 'AVXalign': False, 'NT': False, 'congruent': 11, 'same': False}} {'OP': 'REPM', 'src': {'type': 'addresses_A_ht', 'congruent': 6, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 5, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_WT_ht', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': True}} {'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_A_ht', 'congruent': 4, 'same': False}} {'OP': 'LOAD', 'src': {'type': 'addresses_A_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 4, 'same': False}} {'00': 20382} 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 */
SECTION code_fp_math48 PUBLIC am48_dconst_1_3 EXTERN mm48__ac1_3 ; set AC = 1/3 ; ; uses : bc, de, hl defc am48_dconst_1_3 = mm48__ac1_3
#pragma once #include <GLFW/glfw3.h> #include <spdlog/spdlog.h> #include <vulkan/vulkan.h> #include <cassert> namespace inexor::vulkan_renderer::wrapper { class WindowSurface { private: VkInstance m_instance; VkSurfaceKHR m_surface; public: /// @brief Creates a new window surface. /// @param instance [in] The Vulkan instance. /// @param window [in] The glfw3 window. WindowSurface(const VkInstance instance, GLFWwindow *window); WindowSurface(const WindowSurface &) = delete; WindowSurface(WindowSurface &&) noexcept; ~WindowSurface(); WindowSurface &operator=(const WindowSurface &) = delete; WindowSurface &operator=(WindowSurface &&) = default; [[nodiscard]] VkSurfaceKHR get() const { return m_surface; } const VkSurfaceKHR *operator&() const { return &m_surface; } }; } // namespace inexor::vulkan_renderer::wrapper
/**************************************************************************** * * Copyright (c) 2012-2018 PX4 Development Team. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name PX4 nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file mavlink_main.cpp * MAVLink 1.0 protocol implementation. * * @author Lorenz Meier <lm@inf.ethz.ch> * @author Julian Oes <julian@oes.ch> * @author Anton Babushkin <anton.babushkin@me.com> */ #include <px4_config.h> #include <px4_defines.h> #include <px4_getopt.h> #include <px4_module.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <assert.h> #include <math.h> #include <poll.h> #include <termios.h> #include <time.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <drivers/device/device.h> #include <drivers/drv_hrt.h> #include <arch/board/board.h> #include <parameters/param.h> #include <systemlib/err.h> #include <perf/perf_counter.h> #include <systemlib/mavlink_log.h> #include <lib/ecl/geo/geo.h> #include <dataman/dataman.h> #include <version/version.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/vehicle_command_ack.h> #include <uORB/topics/vehicle_command.h> #include <uORB/topics/mavlink_log.h> #include "mavlink_bridge_header.h" #include "mavlink_main.h" #include "mavlink_messages.h" #include "mavlink_receiver.h" #include "mavlink_rate_limiter.h" #include "mavlink_command_sender.h" // Guard against MAVLink misconfiguration #ifndef MAVLINK_CRC_EXTRA #error MAVLINK_CRC_EXTRA has to be defined on PX4 systems #endif // Guard against flow control misconfiguration #if defined (CRTSCTS) && defined (__PX4_NUTTX) && (CRTSCTS != (CRTS_IFLOW | CCTS_OFLOW)) #error The non-standard CRTSCTS define is incorrect. Fix this in the OS or replace with (CRTS_IFLOW | CCTS_OFLOW) #endif #define DEFAULT_REMOTE_PORT_UDP 14550 ///< GCS port per MAVLink spec #define DEFAULT_DEVICE_NAME "/dev/ttyS1" #define MAX_DATA_RATE 10000000 ///< max data rate in bytes/s #define MAIN_LOOP_DELAY 10000 ///< 100 Hz @ 1000 bytes/s data rate #define FLOW_CONTROL_DISABLE_THRESHOLD 40 ///< picked so that some messages still would fit it. //#define MAVLINK_PRINT_PACKETS static Mavlink *_mavlink_instances = nullptr; /** * mavlink app start / stop handling function * * @ingroup apps */ extern "C" __EXPORT int mavlink_main(int argc, char *argv[]); extern mavlink_system_t mavlink_system; void mavlink_send_uart_bytes(mavlink_channel_t chan, const uint8_t *ch, int length) { Mavlink *m = Mavlink::get_instance(chan); if (m != nullptr) { m->send_bytes(ch, length); #ifdef MAVLINK_PRINT_PACKETS for (unsigned i = 0; i < length; i++) { printf("%02x", (unsigned char)ch[i]); } #endif } } void mavlink_start_uart_send(mavlink_channel_t chan, int length) { Mavlink *m = Mavlink::get_instance(chan); if (m != nullptr) { (void)m->begin_send(); #ifdef MAVLINK_PRINT_PACKETS printf("START PACKET (%u): ", (unsigned)chan); #endif } } void mavlink_end_uart_send(mavlink_channel_t chan, int length) { Mavlink *m = Mavlink::get_instance(chan); if (m != nullptr) { (void)m->send_packet(); #ifdef MAVLINK_PRINT_PACKETS printf("\n"); #endif } } /* * Internal function to give access to the channel status for each channel */ mavlink_status_t *mavlink_get_channel_status(uint8_t channel) { Mavlink *m = Mavlink::get_instance(channel); if (m != nullptr) { return m->get_status(); } else { return nullptr; } } /* * Internal function to give access to the channel buffer for each channel */ mavlink_message_t *mavlink_get_channel_buffer(uint8_t channel) { Mavlink *m = Mavlink::get_instance(channel); if (m != nullptr) { return m->get_buffer(); } else { return nullptr; } } static void usage(); bool Mavlink::_boot_complete = false; bool Mavlink::_config_link_on = false; Mavlink::Mavlink() : _device_name("/dev/ttyS1"), _task_should_exit(false), next(nullptr), _instance_id(0), _transmitting_enabled(true), _transmitting_enabled_commanded(false), _mavlink_log_pub(nullptr), _task_running(false), _mavlink_buffer{}, _mavlink_status{}, _hil_enabled(false), _generate_rc(false), _use_hil_gps(false), _forward_externalsp(false), _is_usb_uart(false), _wait_to_transmit(false), _received_messages(false), _main_loop_delay(1000), _subscriptions(nullptr), _streams(nullptr), _mavlink_shell(nullptr), _mavlink_ulog(nullptr), _mavlink_ulog_stop_requested(false), _mode(MAVLINK_MODE_NORMAL), _channel(MAVLINK_COMM_0), _radio_id(0), _logbuffer(5, sizeof(mavlink_log_s)), _receive_thread{}, _forwarding_on(false), _ftp_on(false), _uart_fd(-1), _baudrate(57600), _datarate(1000), _datarate_events(500), _rate_mult(1.0f), _last_hw_rate_timestamp(0), _mavlink_param_queue_index(0), mavlink_link_termination_allowed(false), _subscribe_to_stream(nullptr), _subscribe_to_stream_rate(0.0f), _udp_initialised(false), _flow_control_mode(Mavlink::FLOW_CONTROL_OFF), _last_write_success_time(0), _last_write_try_time(0), _mavlink_start_time(0), _protocol_version_switch(-1), _protocol_version(0), _bytes_tx(0), _bytes_txerr(0), _bytes_rx(0), _bytes_timestamp(0), _rate_tx(0.0f), _rate_txerr(0.0f), _rate_rx(0.0f), #ifdef __PX4_POSIX _myaddr {}, _src_addr{}, _bcast_addr{}, _src_addr_initialized(false), _broadcast_address_found(false), _broadcast_address_not_found_warned(false), _broadcast_failed_warned(false), _network_buf{}, _network_buf_len(0), #endif _socket_fd(-1), _protocol(SERIAL), _network_port(14556), _remote_port(DEFAULT_REMOTE_PORT_UDP), _rstatus {}, _ping_stats{}, _message_buffer {}, _message_buffer_mutex {}, _send_mutex {}, _param_initialized(false), _broadcast_mode(Mavlink::BROADCAST_MODE_OFF), _param_system_id(PARAM_INVALID), _param_component_id(PARAM_INVALID), _param_radio_id(PARAM_INVALID), _param_system_type(PARAM_INVALID), _param_use_hil_gps(PARAM_INVALID), _param_forward_externalsp(PARAM_INVALID), _param_broadcast(PARAM_INVALID), _system_type(0), /* performance counters */ _loop_perf(perf_alloc(PC_ELAPSED, "mavlink_el")), _txerr_perf(perf_alloc(PC_COUNT, "mavlink_txe")) { _instance_id = Mavlink::instance_count(); /* set channel according to instance id */ switch (_instance_id) { case 0: _channel = MAVLINK_COMM_0; break; case 1: _channel = MAVLINK_COMM_1; break; case 2: _channel = MAVLINK_COMM_2; break; case 3: _channel = MAVLINK_COMM_3; break; #ifdef MAVLINK_COMM_4 case 4: _channel = MAVLINK_COMM_4; break; #endif #ifdef MAVLINK_COMM_5 case 5: _channel = MAVLINK_COMM_5; break; #endif #ifdef MAVLINK_COMM_6 case 6: _channel = MAVLINK_COMM_6; break; #endif default: PX4_WARN("instance ID is out of range"); px4_task_exit(1); break; } _rstatus.type = telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_GENERIC; } Mavlink::~Mavlink() { perf_free(_loop_perf); perf_free(_txerr_perf); if (_task_running) { /* task wakes up every 10ms or so at the longest */ _task_should_exit = true; /* wait for a second for the task to quit at our request */ unsigned i = 0; do { /* wait 20ms */ usleep(20000); /* if we have given up, kill it */ if (++i > 50) { //TODO store main task handle in Mavlink instance to allow killing task //task_delete(_mavlink_task); break; } } while (_task_running); } } void Mavlink::set_proto_version(unsigned version) { if ((version == 1 || version == 0) && ((_protocol_version_switch == 0) || (_protocol_version_switch == 1))) { get_status()->flags |= MAVLINK_STATUS_FLAG_OUT_MAVLINK1; _protocol_version = 1; } else if (version == 2 && ((_protocol_version_switch == 0) || (_protocol_version_switch == 2))) { get_status()->flags &= ~(MAVLINK_STATUS_FLAG_OUT_MAVLINK1); _protocol_version = 2; } } void Mavlink::count_txerr() { perf_count(_txerr_perf); } int Mavlink::instance_count() { unsigned inst_index = 0; Mavlink *inst; LL_FOREACH(::_mavlink_instances, inst) { inst_index++; } return inst_index; } Mavlink * Mavlink::get_instance(int instance) { Mavlink *inst; LL_FOREACH(::_mavlink_instances, inst) { if (instance == inst->get_instance_id()) { return inst; } } return nullptr; } Mavlink * Mavlink::get_instance_for_device(const char *device_name) { Mavlink *inst; LL_FOREACH(::_mavlink_instances, inst) { if (strcmp(inst->_device_name, device_name) == 0) { return inst; } } return nullptr; } Mavlink * Mavlink::get_instance_for_network_port(unsigned long port) { Mavlink *inst; LL_FOREACH(::_mavlink_instances, inst) { if (inst->_network_port == port) { return inst; } } return nullptr; } int Mavlink::destroy_all_instances() { /* start deleting from the end */ Mavlink *inst_to_del = nullptr; Mavlink *next_inst = ::_mavlink_instances; unsigned iterations = 0; PX4_INFO("waiting for instances to stop"); while (next_inst != nullptr) { inst_to_del = next_inst; next_inst = inst_to_del->next; /* set flag to stop thread and wait for all threads to finish */ inst_to_del->_task_should_exit = true; while (inst_to_del->_task_running) { printf("."); fflush(stdout); usleep(10000); iterations++; if (iterations > 1000) { PX4_ERR("Couldn't stop all mavlink instances."); return PX4_ERROR; } } } //we know all threads have exited, so it's safe to manipulate the linked list and delete objects. while (_mavlink_instances) { inst_to_del = _mavlink_instances; LL_DELETE(_mavlink_instances, inst_to_del); delete inst_to_del; } printf("\n"); PX4_INFO("all instances stopped"); return OK; } int Mavlink::get_status_all_instances(bool show_streams_status) { Mavlink *inst = ::_mavlink_instances; unsigned iterations = 0; while (inst != nullptr) { printf("\ninstance #%u:\n", iterations); if (show_streams_status) { inst->display_status_streams(); } else { inst->display_status(); } /* move on */ inst = inst->next; iterations++; } /* return an error if there are no instances */ return (iterations == 0); } bool Mavlink::instance_exists(const char *device_name, Mavlink *self) { Mavlink *inst = ::_mavlink_instances; while (inst != nullptr) { /* don't compare with itself */ if (inst != self && !strcmp(device_name, inst->_device_name)) { return true; } inst = inst->next; } return false; } void Mavlink::forward_message(const mavlink_message_t *msg, Mavlink *self) { Mavlink *inst; LL_FOREACH(_mavlink_instances, inst) { if (inst != self) { const mavlink_msg_entry_t *meta = mavlink_get_msg_entry(msg->msgid); // Extract target system and target component if set int target_system_id = (meta->target_system_ofs != 0) ? ((uint8_t *)msg)[meta->target_system_ofs] : 0; int target_component_id = (meta->target_component_ofs != 0) ? ((uint8_t *)msg)[meta->target_component_ofs] : 233; // Broadcast or addressing this system and not trying to talk // to the autopilot component -> pass on to other components if ((target_system_id == 0 || target_system_id == self->get_system_id()) && (target_component_id == 0 || target_component_id != self->get_component_id())) { inst->pass_message(msg); } } } } int Mavlink::get_uart_fd(unsigned index) { Mavlink *inst = get_instance(index); if (inst) { return inst->get_uart_fd(); } return -1; } int Mavlink::get_uart_fd() { return _uart_fd; } int Mavlink::get_instance_id() { return _instance_id; } mavlink_channel_t Mavlink::get_channel() { return _channel; } void Mavlink::mavlink_update_system() { if (!_param_initialized) { _param_system_id = param_find("MAV_SYS_ID"); _param_component_id = param_find("MAV_COMP_ID"); _param_proto_ver = param_find("MAV_PROTO_VER"); _param_radio_id = param_find("MAV_RADIO_ID"); _param_system_type = param_find("MAV_TYPE"); _param_use_hil_gps = param_find("MAV_USEHILGPS"); _param_forward_externalsp = param_find("MAV_FWDEXTSP"); _param_broadcast = param_find("MAV_BROADCAST"); } /* update system and component id */ int32_t system_id; param_get(_param_system_id, &system_id); int32_t component_id; param_get(_param_component_id, &component_id); int32_t proto = 0; param_get(_param_proto_ver, &proto); if (_protocol_version_switch != proto) { _protocol_version_switch = proto; set_proto_version(proto); } param_get(_param_radio_id, &_radio_id); /* only allow system ID and component ID updates * after reboot - not during operation */ if (!_param_initialized) { if (system_id > 0 && system_id < 255) { mavlink_system.sysid = system_id; } if (component_id > 0 && component_id < 255) { mavlink_system.compid = component_id; } _param_initialized = true; } int32_t system_type; param_get(_param_system_type, &system_type); if (system_type >= 0 && system_type < MAV_TYPE_ENUM_END) { _system_type = system_type; } int32_t use_hil_gps; param_get(_param_use_hil_gps, &use_hil_gps); _use_hil_gps = (bool)use_hil_gps; int32_t forward_externalsp; param_get(_param_forward_externalsp, &forward_externalsp); param_get(_param_broadcast, &_broadcast_mode); _forward_externalsp = (bool)forward_externalsp; } int Mavlink::get_system_id() { return mavlink_system.sysid; } int Mavlink::get_component_id() { return mavlink_system.compid; } int Mavlink::mavlink_open_uart(int baud, const char *uart_name, bool force_flow_control) { #ifndef B460800 #define B460800 460800 #endif #ifndef B500000 #define B500000 500000 #endif #ifndef B921600 #define B921600 921600 #endif #ifndef B1000000 #define B1000000 1000000 #endif /* process baud rate */ int speed; switch (baud) { case 0: speed = B0; break; case 50: speed = B50; break; case 75: speed = B75; break; case 110: speed = B110; break; case 134: speed = B134; break; case 150: speed = B150; break; case 200: speed = B200; break; case 300: speed = B300; break; case 600: speed = B600; break; case 1200: speed = B1200; break; case 1800: speed = B1800; break; case 2400: speed = B2400; break; case 4800: speed = B4800; break; case 9600: speed = B9600; break; case 19200: speed = B19200; break; case 38400: speed = B38400; break; case 57600: speed = B57600; break; case 115200: speed = B115200; break; case 230400: speed = B230400; break; case 460800: speed = B460800; break; case 500000: speed = B500000; break; case 921600: speed = B921600; break; case 1000000: speed = B1000000; break; #ifdef B1500000 case 1500000: speed = B1500000; break; #endif #ifdef B3000000 case 3000000: speed = B3000000; break; #endif default: PX4_ERR("Unsupported baudrate: %d\n\tsupported examples:\n\t9600, 19200, 38400, 57600\t\n115200\n230400\n460800\n500000\n921600\n1000000\n", baud); return -EINVAL; } /* back off 1800 ms to avoid running into the USB setup timing */ while (_mode == MAVLINK_MODE_CONFIG && hrt_absolute_time() < 1800U * 1000U) { usleep(50000); } /* open uart */ _uart_fd = ::open(uart_name, O_RDWR | O_NOCTTY); /* if this is a config link, stay here and wait for it to open */ if (_uart_fd < 0 && _mode == MAVLINK_MODE_CONFIG) { int armed_sub = orb_subscribe(ORB_ID(actuator_armed)); struct actuator_armed_s armed; /* get the system arming state and abort on arming */ while (_uart_fd < 0) { /* abort if an arming topic is published and system is armed */ bool updated = false; orb_check(armed_sub, &updated); if (updated) { /* the system is now providing arming status feedback. * instead of timing out, we resort to abort bringing * up the terminal. */ orb_copy(ORB_ID(actuator_armed), armed_sub, &armed); if (armed.armed) { /* this is not an error, but we are done */ orb_unsubscribe(armed_sub); return -1; } } usleep(100000); _uart_fd = ::open(uart_name, O_RDWR | O_NOCTTY); } orb_unsubscribe(armed_sub); } if (_uart_fd < 0) { return _uart_fd; } /* Try to set baud rate */ struct termios uart_config; int termios_state; _is_usb_uart = false; /* Initialize the uart config */ if ((termios_state = tcgetattr(_uart_fd, &uart_config)) < 0) { PX4_ERR("ERR GET CONF %s: %d\n", uart_name, termios_state); ::close(_uart_fd); return -1; } /* Clear ONLCR flag (which appends a CR for every LF) */ uart_config.c_oflag &= ~ONLCR; /* USB serial is indicated by /dev/ttyACM0*/ if (strcmp(uart_name, "/dev/ttyACM0") != OK && strcmp(uart_name, "/dev/ttyACM1") != OK) { /* Set baud rate */ if (cfsetispeed(&uart_config, speed) < 0 || cfsetospeed(&uart_config, speed) < 0) { PX4_ERR("ERR SET BAUD %s: %d\n", uart_name, termios_state); ::close(_uart_fd); return -1; } } else { _is_usb_uart = true; /* USB has no baudrate, but use a magic number for 'fast' */ _baudrate = 2000000; _rstatus.type = telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_USB; } #if defined(__PX4_LINUX) || defined(__PX4_DARWIN) || defined(__PX4_CYGWIN) /* Put in raw mode */ cfmakeraw(&uart_config); #endif if ((termios_state = tcsetattr(_uart_fd, TCSANOW, &uart_config)) < 0) { PX4_WARN("ERR SET CONF %s\n", uart_name); ::close(_uart_fd); return -1; } /* * Setup hardware flow control. If the port has no RTS pin this call will fail, * which is not an issue, but requires a separate call so we can fail silently. */ /* setup output flow control */ if (enable_flow_control(force_flow_control ? FLOW_CONTROL_ON : FLOW_CONTROL_AUTO)) { PX4_WARN("hardware flow control not supported"); } return _uart_fd; } int Mavlink::enable_flow_control(enum FLOW_CONTROL_MODE mode) { // We can't do this on USB - skip if (_is_usb_uart) { _flow_control_mode = FLOW_CONTROL_OFF; return OK; } struct termios uart_config; int ret = tcgetattr(_uart_fd, &uart_config); if (mode) { uart_config.c_cflag |= CRTSCTS; } else { uart_config.c_cflag &= ~CRTSCTS; } ret = tcsetattr(_uart_fd, TCSANOW, &uart_config); if (!ret) { _flow_control_mode = mode; } return ret; } int Mavlink::set_hil_enabled(bool hil_enabled) { int ret = OK; /* enable HIL (only on links with sufficient bandwidth) */ if (hil_enabled && !_hil_enabled && _datarate > 5000) { _hil_enabled = true; ret = configure_stream("HIL_ACTUATOR_CONTROLS", 200.0f); } /* disable HIL */ if (!hil_enabled && _hil_enabled) { _hil_enabled = false; ret = configure_stream("HIL_ACTUATOR_CONTROLS", 0.0f); } return ret; } unsigned Mavlink::get_free_tx_buf() { /* * Check if the OS buffer is full and disable HW * flow control if it continues to be full */ int buf_free = 0; // if we are using network sockets, return max length of one packet if (get_protocol() == UDP || get_protocol() == TCP) { return 1500; } else { // No FIONSPACE on Linux todo:use SIOCOUTQ and queue size to emulate FIONSPACE #if defined(__PX4_LINUX) || defined(__PX4_DARWIN) || defined(__PX4_CYGWIN) //Linux cp210x does not support TIOCOUTQ buf_free = 256; #else (void) ioctl(_uart_fd, FIONSPACE, (unsigned long)&buf_free); #endif if (_flow_control_mode == FLOW_CONTROL_AUTO && buf_free < FLOW_CONTROL_DISABLE_THRESHOLD) { /* Disable hardware flow control in FLOW_CONTROL_AUTO mode: * if no successful write since a defined time * and if the last try was not the last successful write */ if (_last_write_try_time != 0 && hrt_elapsed_time(&_last_write_success_time) > 500 * 1000UL && _last_write_success_time != _last_write_try_time) { enable_flow_control(FLOW_CONTROL_OFF); } } } return buf_free; } void Mavlink::begin_send() { // must protect the network buffer so other calls from receive_thread do not // mangle the message. pthread_mutex_lock(&_send_mutex); } int Mavlink::send_packet() { int ret = -1; #ifdef __PX4_POSIX /* Only send packets if there is something in the buffer. */ if (_network_buf_len == 0) { pthread_mutex_unlock(&_send_mutex); return 0; } if (get_protocol() == UDP) { ret = sendto(_socket_fd, _network_buf, _network_buf_len, 0, (struct sockaddr *)&_src_addr, sizeof(_src_addr)); struct telemetry_status_s &tstatus = get_rx_status(); /* resend message via broadcast if no valid connection exists */ if ((_mode != MAVLINK_MODE_ONBOARD) && broadcast_enabled() && (!get_client_source_initialized() || (hrt_elapsed_time(&tstatus.heartbeat_time) > 3 * 1000 * 1000))) { if (!_broadcast_address_found) { find_broadcast_address(); } if (_broadcast_address_found && _network_buf_len > 0) { int bret = sendto(_socket_fd, _network_buf, _network_buf_len, 0, (struct sockaddr *)&_bcast_addr, sizeof(_bcast_addr)); if (bret <= 0) { if (!_broadcast_failed_warned) { PX4_ERR("sending broadcast failed, errno: %d: %s", errno, strerror(errno)); _broadcast_failed_warned = true; } } else { _broadcast_failed_warned = false; } } } } else if (get_protocol() == TCP) { /* not implemented, but possible to do so */ PX4_ERR("TCP transport pending implementation"); } _network_buf_len = 0; #endif pthread_mutex_unlock(&_send_mutex); return ret; } void Mavlink::send_bytes(const uint8_t *buf, unsigned packet_len) { /* If the wait until transmit flag is on, only transmit after we've received messages. Otherwise, transmit all the time. */ if (!should_transmit()) { return; } _last_write_try_time = hrt_absolute_time(); if (_mavlink_start_time == 0) { _mavlink_start_time = _last_write_try_time; } if (get_protocol() == SERIAL) { /* check if there is space in the buffer, let it overflow else */ unsigned buf_free = get_free_tx_buf(); if (buf_free < packet_len) { /* not enough space in buffer to send */ count_txerr(); count_txerrbytes(packet_len); return; } } size_t ret = -1; /* send message to UART */ if (get_protocol() == SERIAL) { ret = ::write(_uart_fd, buf, packet_len); } #ifdef __PX4_POSIX else { if (_network_buf_len + packet_len < sizeof(_network_buf) / sizeof(_network_buf[0])) { memcpy(&_network_buf[_network_buf_len], buf, packet_len); _network_buf_len += packet_len; ret = packet_len; } } #endif if (ret != (size_t) packet_len) { count_txerr(); count_txerrbytes(packet_len); } else { _last_write_success_time = _last_write_try_time; count_txbytes(packet_len); } } void Mavlink::find_broadcast_address() { #if defined(__PX4_LINUX) || defined(__PX4_DARWIN) || defined(__PX4_CYGWIN) struct ifconf ifconf; int ret; #if defined(__APPLE__) && defined(__MACH__) // On Mac, we can't determine the required buffer // size in advance, so we just use what tends to work. ifconf.ifc_len = 1024; #else // On Linux, we can determine the required size of the // buffer first by providing NULL to ifc_req. ifconf.ifc_req = nullptr; ifconf.ifc_len = 0; ret = ioctl(_socket_fd, SIOCGIFCONF, &ifconf); if (ret != 0) { PX4_WARN("getting required buffer size failed"); return; } #endif PX4_DEBUG("need to allocate %d bytes", ifconf.ifc_len); // Allocate buffer. ifconf.ifc_req = (struct ifreq *)(new uint8_t[ifconf.ifc_len]); if (ifconf.ifc_req == nullptr) { PX4_ERR("Could not allocate ifconf buffer"); return; } memset(ifconf.ifc_req, 0, ifconf.ifc_len); ret = ioctl(_socket_fd, SIOCGIFCONF, &ifconf); if (ret != 0) { PX4_ERR("getting network config failed"); delete[] ifconf.ifc_req; return; } int offset = 0; // Later used to point to next network interface in buffer. struct ifreq *cur_ifreq = (struct ifreq *) & (((uint8_t *)ifconf.ifc_req)[offset]); // The ugly `for` construct is used because it allows to use // `continue` and `break`. for (; offset < ifconf.ifc_len; #if defined(__APPLE__) && defined(__MACH__) // On Mac, to get to next entry in buffer, jump by the size of // the interface name size plus whatever is greater, either the // sizeof sockaddr or ifr_addr.sa_len. offset += IF_NAMESIZE + (sizeof(struct sockaddr) > cur_ifreq->ifr_addr.sa_len ? sizeof(struct sockaddr) : cur_ifreq->ifr_addr.sa_len) #else // On Linux, it's much easier to traverse the buffer, every entry // has the constant length. offset += sizeof(struct ifreq) #endif ) { // Point to next network interface in buffer. cur_ifreq = (struct ifreq *) & (((uint8_t *)ifconf.ifc_req)[offset]); PX4_DEBUG("looking at %s", cur_ifreq->ifr_name); // ignore loopback network if (strcmp(cur_ifreq->ifr_name, "lo") == 0 || strcmp(cur_ifreq->ifr_name, "lo0") == 0 || strcmp(cur_ifreq->ifr_name, "lo1") == 0 || strcmp(cur_ifreq->ifr_name, "lo2") == 0) { PX4_DEBUG("skipping loopback"); continue; } struct in_addr &sin_addr = ((struct sockaddr_in *)&cur_ifreq->ifr_addr)->sin_addr; // Accept network interfaces to local network only. This means it's an IP starting with: // 192./172./10. // Also see https://tools.ietf.org/html/rfc1918#section-3 uint8_t first_byte = sin_addr.s_addr & 0xFF; if (first_byte != 192 && first_byte != 172 && first_byte != 10) { continue; } if (!_broadcast_address_found) { const struct in_addr netmask_addr = query_netmask_addr(_socket_fd, *cur_ifreq); const struct in_addr broadcast_addr = compute_broadcast_addr(sin_addr, netmask_addr); PX4_INFO("using network interface %s, IP: %s", cur_ifreq->ifr_name, inet_ntoa(sin_addr)); PX4_INFO("with netmask: %s", inet_ntoa(netmask_addr)); PX4_INFO("and broadcast IP: %s", inet_ntoa(broadcast_addr)); _bcast_addr.sin_family = AF_INET; _bcast_addr.sin_addr = broadcast_addr; _broadcast_address_found = true; } else { PX4_DEBUG("ignoring additional network interface %s, IP: %s", cur_ifreq->ifr_name, inet_ntoa(sin_addr)); } } if (_broadcast_address_found) { _bcast_addr.sin_port = htons(_remote_port); int broadcast_opt = 1; if (setsockopt(_socket_fd, SOL_SOCKET, SO_BROADCAST, &broadcast_opt, sizeof(broadcast_opt)) < 0) { PX4_WARN("setting broadcast permission failed"); } _broadcast_address_not_found_warned = false; } else { if (!_broadcast_address_not_found_warned) { PX4_WARN("no broadcasting address found"); _broadcast_address_not_found_warned = true; } } delete[] ifconf.ifc_req; #endif } #ifdef __PX4_POSIX const in_addr Mavlink::query_netmask_addr(const int socket_fd, const ifreq &ifreq) { struct ifreq netmask_ifreq; memset(&netmask_ifreq, 0, sizeof(netmask_ifreq)); strncpy(netmask_ifreq.ifr_name, ifreq.ifr_name, IF_NAMESIZE); ioctl(socket_fd, SIOCGIFNETMASK, &netmask_ifreq); return ((struct sockaddr_in *)&netmask_ifreq.ifr_addr)->sin_addr; } const in_addr Mavlink::compute_broadcast_addr(const in_addr &host_addr, const in_addr &netmask_addr) { struct in_addr broadcast_addr; broadcast_addr.s_addr = ~netmask_addr.s_addr | host_addr.s_addr; return broadcast_addr; } #endif void Mavlink::init_udp() { #if defined (__PX4_LINUX) || defined (__PX4_DARWIN) || defined(__PX4_CYGWIN) PX4_DEBUG("Setting up UDP with port %d", _network_port); _myaddr.sin_family = AF_INET; _myaddr.sin_addr.s_addr = htonl(INADDR_ANY); _myaddr.sin_port = htons(_network_port); if ((_socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { PX4_WARN("create socket failed: %s", strerror(errno)); return; } if (bind(_socket_fd, (struct sockaddr *)&_myaddr, sizeof(_myaddr)) < 0) { PX4_WARN("bind failed: %s", strerror(errno)); return; } /* set default target address, but not for onboard mode (will be set on first received packet) */ if (!_src_addr_initialized) { _src_addr.sin_family = AF_INET; inet_aton("127.0.0.1", &_src_addr.sin_addr); } _src_addr.sin_port = htons(_remote_port); #endif } void Mavlink::handle_message(const mavlink_message_t *msg) { if (!accepting_commands()) { return; } /* * NOTE: this is called from the receiver thread */ if (get_forwarding_on()) { /* forward any messages to other mavlink instances */ Mavlink::forward_message(msg, this); } } void Mavlink::send_statustext_info(const char *string) { mavlink_log_info(&_mavlink_log_pub, string); } void Mavlink::send_statustext_critical(const char *string) { mavlink_log_critical(&_mavlink_log_pub, string); PX4_ERR(string); } void Mavlink::send_statustext_emergency(const char *string) { mavlink_log_emergency(&_mavlink_log_pub, string); } void Mavlink::send_autopilot_capabilites() { struct vehicle_status_s status; MavlinkOrbSubscription *status_sub = this->add_orb_subscription(ORB_ID(vehicle_status)); if (status_sub->update(&status)) { mavlink_autopilot_version_t msg = {}; msg.capabilities = MAV_PROTOCOL_CAPABILITY_MISSION_FLOAT; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_MISSION_INT; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_PARAM_FLOAT; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_COMMAND_INT; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_FTP; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_SET_ATTITUDE_TARGET; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_SET_POSITION_TARGET_LOCAL_NED; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_SET_ACTUATOR_TARGET; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_MAVLINK2; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_MISSION_FENCE; msg.capabilities |= MAV_PROTOCOL_CAPABILITY_MISSION_RALLY; msg.flight_sw_version = px4_firmware_version(); msg.middleware_sw_version = px4_firmware_version(); msg.os_sw_version = px4_os_version(); msg.board_version = px4_board_version(); uint64_t fw_git_version_binary = px4_firmware_version_binary(); memcpy(&msg.flight_custom_version, &fw_git_version_binary, sizeof(msg.flight_custom_version)); memcpy(&msg.middleware_custom_version, &fw_git_version_binary, sizeof(msg.middleware_custom_version)); uint64_t os_git_version_binary = px4_os_version_binary(); memcpy(&msg.os_custom_version, &os_git_version_binary, sizeof(msg.os_custom_version)); #ifdef CONFIG_CDCACM_VENDORID msg.vendor_id = CONFIG_CDCACM_VENDORID; #else msg.vendor_id = 0; #endif #ifdef CONFIG_CDCACM_PRODUCTID msg.product_id = CONFIG_CDCACM_PRODUCTID; #else msg.product_id = 0; #endif uuid_uint32_t uid; board_get_uuid32(uid); msg.uid = (((uint64_t)uid[PX4_CPU_UUID_WORD32_UNIQUE_M]) << 32) | uid[PX4_CPU_UUID_WORD32_UNIQUE_H]; mavlink_msg_autopilot_version_send_struct(get_channel(), &msg); } } void Mavlink::send_protocol_version() { mavlink_protocol_version_t msg = {}; msg.version = _protocol_version * 100; msg.min_version = 100; msg.max_version = 200; uint64_t mavlink_lib_git_version_binary = px4_mavlink_lib_version_binary(); // TODO add when available //memcpy(&msg.spec_version_hash, &mavlink_spec_git_version_binary, sizeof(msg.spec_version_hash)); memcpy(&msg.library_version_hash, &mavlink_lib_git_version_binary, sizeof(msg.library_version_hash)); // Switch to MAVLink 2 int curr_proto_ver = _protocol_version; set_proto_version(2); // Send response - if it passes through the link its fine to use MAVLink 2 mavlink_msg_protocol_version_send_struct(get_channel(), &msg); // Reset to previous value set_proto_version(curr_proto_ver); } MavlinkOrbSubscription *Mavlink::add_orb_subscription(const orb_id_t topic, int instance, bool disable_sharing) { if (!disable_sharing) { /* check if already subscribed to this topic */ MavlinkOrbSubscription *sub; LL_FOREACH(_subscriptions, sub) { if (sub->get_topic() == topic && sub->get_instance() == instance) { /* already subscribed */ return sub; } } } /* add new subscription */ MavlinkOrbSubscription *sub_new = new MavlinkOrbSubscription(topic, instance); LL_APPEND(_subscriptions, sub_new); return sub_new; } int Mavlink::interval_from_rate(float rate) { if (rate > 0.000001f) { return (1000000.0f / rate); } else if (rate < 0.0f) { return -1; } else { return 0; } } int Mavlink::configure_stream(const char *stream_name, const float rate) { PX4_DEBUG("configure_stream(%s, %.3f)", stream_name, (double)rate); /* calculate interval in us, -1 means unlimited stream, 0 means disabled */ int interval = interval_from_rate(rate); /* search if stream exists */ MavlinkStream *stream; LL_FOREACH(_streams, stream) { if (strcmp(stream_name, stream->get_name()) == 0) { if (interval != 0) { /* set new interval */ stream->set_interval(interval); } else { /* delete stream */ LL_DELETE(_streams, stream); delete stream; } return OK; } } if (interval == 0) { /* stream was not active and is requested to be disabled, do nothing */ return OK; } // search for stream with specified name in supported streams list // create new instance if found stream = create_mavlink_stream(stream_name, this); if (stream != nullptr) { stream->set_interval(interval); LL_APPEND(_streams, stream); return OK; } /* if we reach here, the stream list does not contain the stream */ PX4_WARN("stream %s not found", stream_name); return PX4_ERROR; } void Mavlink::adjust_stream_rates(const float multiplier) { /* do not allow to push us to zero */ if (multiplier < MAVLINK_MIN_MULTIPLIER) { return; } /* search if stream exists */ MavlinkStream *stream; LL_FOREACH(_streams, stream) { /* set new interval */ int interval = stream->get_interval(); if (interval > 0) { interval /= multiplier; /* limit min / max interval */ if (interval < MAVLINK_MIN_INTERVAL) { interval = MAVLINK_MIN_INTERVAL; } if (interval > MAVLINK_MAX_INTERVAL) { interval = MAVLINK_MAX_INTERVAL; } /* set new interval */ stream->set_interval(interval); } } } void Mavlink::configure_stream_threadsafe(const char *stream_name, const float rate) { /* orb subscription must be done from the main thread, * set _subscribe_to_stream and _subscribe_to_stream_rate fields * which polled in mavlink main loop */ if (!_task_should_exit) { /* wait for previous subscription completion */ while (_subscribe_to_stream != nullptr) { usleep(MAIN_LOOP_DELAY / 2); } /* copy stream name */ unsigned n = strlen(stream_name) + 1; char *s = new char[n]; strcpy(s, stream_name); /* set subscription task */ _subscribe_to_stream_rate = rate; _subscribe_to_stream = s; /* wait for subscription */ do { usleep(MAIN_LOOP_DELAY / 2); } while (_subscribe_to_stream != nullptr); delete[] s; } } int Mavlink::message_buffer_init(int size) { _message_buffer.size = size; _message_buffer.write_ptr = 0; _message_buffer.read_ptr = 0; _message_buffer.data = (char *)malloc(_message_buffer.size); int ret; if (_message_buffer.data == nullptr) { ret = PX4_ERROR; _message_buffer.size = 0; } else { ret = OK; } return ret; } void Mavlink::message_buffer_destroy() { _message_buffer.size = 0; _message_buffer.write_ptr = 0; _message_buffer.read_ptr = 0; free(_message_buffer.data); } int Mavlink::message_buffer_count() { int n = _message_buffer.write_ptr - _message_buffer.read_ptr; if (n < 0) { n += _message_buffer.size; } return n; } int Mavlink::message_buffer_is_empty() { return _message_buffer.read_ptr == _message_buffer.write_ptr; } bool Mavlink::message_buffer_write(const void *ptr, int size) { // bytes available to write int available = _message_buffer.read_ptr - _message_buffer.write_ptr - 1; if (available < 0) { available += _message_buffer.size; } if (size > available) { // buffer overflow return false; } char *c = (char *) ptr; int n = _message_buffer.size - _message_buffer.write_ptr; // bytes to end of the buffer if (n < size) { // message goes over end of the buffer memcpy(&(_message_buffer.data[_message_buffer.write_ptr]), c, n); _message_buffer.write_ptr = 0; } else { n = 0; } // now: n = bytes already written int p = size - n; // number of bytes to write memcpy(&(_message_buffer.data[_message_buffer.write_ptr]), &(c[n]), p); _message_buffer.write_ptr = (_message_buffer.write_ptr + p) % _message_buffer.size; return true; } int Mavlink::message_buffer_get_ptr(void **ptr, bool *is_part) { // bytes available to read int available = _message_buffer.write_ptr - _message_buffer.read_ptr; if (available == 0) { return 0; // buffer is empty } int n = 0; if (available > 0) { // read pointer is before write pointer, all available bytes can be read n = available; *is_part = false; } else { // read pointer is after write pointer, read bytes from read_ptr to end of the buffer n = _message_buffer.size - _message_buffer.read_ptr; *is_part = _message_buffer.write_ptr > 0; } *ptr = &(_message_buffer.data[_message_buffer.read_ptr]); return n; } void Mavlink::message_buffer_mark_read(int n) { _message_buffer.read_ptr = (_message_buffer.read_ptr + n) % _message_buffer.size; } void Mavlink::pass_message(const mavlink_message_t *msg) { if (_forwarding_on) { /* size is 8 bytes plus variable payload */ int size = MAVLINK_NUM_NON_PAYLOAD_BYTES + msg->len; pthread_mutex_lock(&_message_buffer_mutex); message_buffer_write(msg, size); pthread_mutex_unlock(&_message_buffer_mutex); } } float Mavlink::get_rate_mult() { return _rate_mult; } MavlinkShell * Mavlink::get_shell() { if (!_mavlink_shell) { _mavlink_shell = new MavlinkShell(); if (!_mavlink_shell) { PX4_ERR("Failed to allocate a shell"); } else { int ret = _mavlink_shell->start(); if (ret != 0) { PX4_ERR("Failed to start shell (%i)", ret); delete _mavlink_shell; _mavlink_shell = nullptr; } } } return _mavlink_shell; } void Mavlink::close_shell() { if (_mavlink_shell) { delete _mavlink_shell; _mavlink_shell = nullptr; } } void Mavlink::update_rate_mult() { float const_rate = 0.0f; float rate = 0.0f; /* scale down rates if their theoretical bandwidth is exceeding the link bandwidth */ MavlinkStream *stream; LL_FOREACH(_streams, stream) { if (stream->const_rate()) { const_rate += (stream->get_interval() > 0) ? stream->get_size_avg() * 1000000.0f / stream->get_interval() : 0; } else { rate += (stream->get_interval() > 0) ? stream->get_size_avg() * 1000000.0f / stream->get_interval() : 0; } } float mavlink_ulog_streaming_rate_inv = 1.0f; if (_mavlink_ulog) { mavlink_ulog_streaming_rate_inv = 1.f - _mavlink_ulog->current_data_rate(); } /* scale up and down as the link permits */ float bandwidth_mult = (float)(_datarate * mavlink_ulog_streaming_rate_inv - const_rate) / rate; /* if we do not have flow control, limit to the set data rate */ if (!get_flow_control_enabled()) { bandwidth_mult = fminf(1.0f, bandwidth_mult); } /* check if we have radio feedback */ struct telemetry_status_s &tstatus = get_rx_status(); bool radio_critical = false; bool radio_found = false; /* 2nd pass: Now check hardware limits */ if (tstatus.type == telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_3DR_RADIO) { radio_found = true; if (tstatus.txbuf < RADIO_BUFFER_LOW_PERCENTAGE) { radio_critical = true; } } float hardware_mult = _rate_mult; /* scale down if we have a TX err rate suggesting link congestion */ if (_rate_txerr > 0.0f && !radio_critical) { hardware_mult = (_rate_tx) / (_rate_tx + _rate_txerr); } else if (radio_found && tstatus.telem_time != _last_hw_rate_timestamp) { if (tstatus.txbuf < RADIO_BUFFER_CRITICAL_LOW_PERCENTAGE) { /* this indicates link congestion, reduce rate by 20% */ hardware_mult *= 0.80f; } else if (tstatus.txbuf < RADIO_BUFFER_LOW_PERCENTAGE) { /* this indicates link congestion, reduce rate by 2.5% */ hardware_mult *= 0.975f; } else if (tstatus.txbuf > RADIO_BUFFER_HALF_PERCENTAGE) { /* this indicates spare bandwidth, increase by 2.5% */ hardware_mult *= 1.025f; /* limit to a max multiplier of 1 */ hardware_mult = fminf(1.0f, hardware_mult); } } else if (!radio_found) { /* no limitation, set hardware to 1 */ hardware_mult = 1.0f; } _last_hw_rate_timestamp = tstatus.telem_time; /* pick the minimum from bandwidth mult and hardware mult as limit */ _rate_mult = fminf(bandwidth_mult, hardware_mult); /* ensure the rate multiplier never drops below 5% so that something is always sent */ _rate_mult = fmaxf(0.05f, _rate_mult); } int Mavlink::configure_streams_to_default(const char *configure_single_stream) { int ret = 0; bool stream_configured = false; auto configure_stream_local = [&stream_configured, configure_single_stream, &ret, this](const char *stream_name, float rate) { if (!configure_single_stream || strcmp(configure_single_stream, stream_name) == 0) { int ret_local = configure_stream(stream_name, rate); if (ret_local != 0) { ret = ret_local; } stream_configured = true; } }; const float unlimited_rate = -1.f; switch (_mode) { case MAVLINK_MODE_NORMAL: configure_stream_local("ADSB_VEHICLE", unlimited_rate); configure_stream_local("ALTITUDE", 1.0f); configure_stream_local("ATTITUDE", 20.0f); configure_stream_local("ATTITUDE_TARGET", 2.0f); configure_stream_local("CAMERA_IMAGE_CAPTURED", unlimited_rate); configure_stream_local("COLLISION", unlimited_rate); configure_stream_local("DEBUG", 1.0f); configure_stream_local("DEBUG_VECT", 1.0f); configure_stream_local("DISTANCE_SENSOR", 0.5f); configure_stream_local("ESTIMATOR_STATUS", 0.5f); configure_stream_local("EXTENDED_SYS_STATE", 1.0f); configure_stream_local("GLOBAL_POSITION_INT", 5.0f); configure_stream_local("GPS_RAW_INT", 1.0f); configure_stream_local("HIGHRES_IMU", 1.5f); configure_stream_local("HOME_POSITION", 0.5f); configure_stream_local("LOCAL_POSITION_NED", 1.0f); configure_stream_local("NAMED_VALUE_FLOAT", 1.0f); configure_stream_local("NAV_CONTROLLER_OUTPUT", 1.5f); configure_stream_local("OPTICAL_FLOW_RAD", 1.0f); configure_stream_local("PING", 0.1f); configure_stream_local("POSITION_TARGET_LOCAL_NED", 1.5f); configure_stream_local("POSITION_TARGET_GLOBAL_INT", 1.5f); configure_stream_local("RC_CHANNELS", 5.0f); configure_stream_local("SERVO_OUTPUT_RAW_0", 1.0f); configure_stream_local("SYS_STATUS", 1.0f); configure_stream_local("TRAJECTORY_REPRESENTATION_WAYPOINTS", 5.0f); configure_stream_local("VFR_HUD", 4.0f); configure_stream_local("VISION_POSITION_ESTIMATE", 1.0f); configure_stream_local("WIND_COV", 1.0f); break; case MAVLINK_MODE_ONBOARD: configure_stream_local("ACTUATOR_CONTROL_TARGET0", 10.0f); configure_stream_local("ADSB_VEHICLE", unlimited_rate); configure_stream_local("ALTITUDE", 10.0f); configure_stream_local("ATTITUDE", 100.0f); configure_stream_local("ATTITUDE_QUATERNION", 50.0f); configure_stream_local("ATTITUDE_TARGET", 10.0f); configure_stream_local("CAMERA_CAPTURE", 2.0f); configure_stream_local("CAMERA_IMAGE_CAPTURED", unlimited_rate); configure_stream_local("CAMERA_TRIGGER", unlimited_rate); configure_stream_local("COLLISION", unlimited_rate); configure_stream_local("DEBUG", 10.0f); configure_stream_local("DEBUG_VECT", 10.0f); configure_stream_local("DISTANCE_SENSOR", 10.0f); configure_stream_local("ESTIMATOR_STATUS", 1.0f); configure_stream_local("EXTENDED_SYS_STATE", 5.0f); configure_stream_local("GLOBAL_POSITION_INT", 50.0f); configure_stream_local("GPS_RAW_INT", unlimited_rate); configure_stream_local("HIGHRES_IMU", 50.0f); configure_stream_local("HOME_POSITION", 0.5f); configure_stream_local("LOCAL_POSITION_NED", 30.0f); configure_stream_local("NAMED_VALUE_FLOAT", 10.0f); configure_stream_local("NAV_CONTROLLER_OUTPUT", 10.0f); configure_stream_local("OPTICAL_FLOW_RAD", 10.0f); configure_stream_local("PING", 1.0f); configure_stream_local("POSITION_TARGET_GLOBAL_INT", 10.0f); configure_stream_local("POSITION_TARGET_LOCAL_NED", 10.0f); configure_stream_local("RC_CHANNELS", 20.0f); configure_stream_local("SCALED_IMU", 50.0f); configure_stream_local("SERVO_OUTPUT_RAW_0", 10.0f); configure_stream_local("SYS_STATUS", 5.0f); configure_stream_local("SYSTEM_TIME", 1.0f); configure_stream_local("TIMESYNC", 10.0f); configure_stream_local("TRAJECTORY_REPRESENTATION_WAYPOINTS", 5.0f); configure_stream_local("VFR_HUD", 10.0f); configure_stream_local("VISION_POSITION_ESTIMATE", 10.0f); configure_stream_local("WIND_COV", 10.0f); break; case MAVLINK_MODE_OSD: configure_stream_local("ALTITUDE", 1.0f); configure_stream_local("ATTITUDE", 25.0f); configure_stream_local("ATTITUDE_TARGET", 10.0f); configure_stream_local("ESTIMATOR_STATUS", 1.0f); configure_stream_local("EXTENDED_SYS_STATE", 1.0f); configure_stream_local("GLOBAL_POSITION_INT", 10.0f); configure_stream_local("GPS_RAW_INT", 1.0f); configure_stream_local("HOME_POSITION", 0.5f); configure_stream_local("RC_CHANNELS", 5.0f); configure_stream_local("SERVO_OUTPUT_RAW_0", 1.0f); configure_stream_local("SYS_STATUS", 5.0f); configure_stream_local("SYSTEM_TIME", 1.0f); configure_stream_local("VFR_HUD", 25.0f); configure_stream_local("WIND_COV", 2.0f); break; case MAVLINK_MODE_MAGIC: /* fallthrough */ case MAVLINK_MODE_CUSTOM: //stream nothing break; case MAVLINK_MODE_CONFIG: // Enable a number of interesting streams we want via USB configure_stream_local("ACTUATOR_CONTROL_TARGET0", 30.0f); configure_stream_local("ADSB_VEHICLE", unlimited_rate); configure_stream_local("ALTITUDE", 10.0f); configure_stream_local("ATTITUDE", 50.0f); configure_stream_local("ATTITUDE_TARGET", 8.0f); configure_stream_local("ATTITUDE_QUATERNION", 50.0f); configure_stream_local("CAMERA_TRIGGER", unlimited_rate); configure_stream_local("CAMERA_IMAGE_CAPTURED", unlimited_rate); configure_stream_local("COLLISION", unlimited_rate); configure_stream_local("DEBUG", 50.0f); configure_stream_local("DEBUG_VECT", 50.0f); configure_stream_local("DISTANCE_SENSOR", 10.0f); configure_stream_local("GPS_RAW_INT", unlimited_rate); configure_stream_local("ESTIMATOR_STATUS", 5.0f); configure_stream_local("EXTENDED_SYS_STATE", 2.0f); configure_stream_local("GLOBAL_POSITION_INT", 10.0f); configure_stream_local("HIGHRES_IMU", 50.0f); configure_stream_local("HOME_POSITION", 0.5f); configure_stream_local("LOCAL_POSITION_NED", 30.0f); configure_stream_local("MANUAL_CONTROL", 5.0f); configure_stream_local("NAMED_VALUE_FLOAT", 50.0f); configure_stream_local("NAV_CONTROLLER_OUTPUT", 10.0f); configure_stream_local("OPTICAL_FLOW_RAD", 10.0f); configure_stream_local("PING", 1.0f); configure_stream_local("POSITION_TARGET_GLOBAL_INT", 10.0f); configure_stream_local("RC_CHANNELS", 10.0f); configure_stream_local("SERVO_OUTPUT_RAW_0", 20.0f); configure_stream_local("SERVO_OUTPUT_RAW_1", 20.0f); configure_stream_local("SYS_STATUS", 1.0f); configure_stream_local("SYSTEM_TIME", 1.0f); configure_stream_local("TIMESYNC", 10.0f); configure_stream_local("VFR_HUD", 20.0f); configure_stream_local("VISION_POSITION_ESTIMATE", 10.0f); configure_stream_local("WIND_COV", 10.0f); break; case MAVLINK_MODE_IRIDIUM: configure_stream_local("HIGH_LATENCY2", 0.015f); break; case MAVLINK_MODE_MINIMAL: configure_stream_local("ALTITUDE", 0.5f); configure_stream_local("ATTITUDE", 10.0f); configure_stream_local("EXTENDED_SYS_STATE", 0.1f); configure_stream_local("GPS_RAW_INT", 0.5f); configure_stream_local("GLOBAL_POSITION_INT", 5.0f); configure_stream_local("HOME_POSITION", 0.1f); configure_stream_local("NAMED_VALUE_FLOAT", 1.0f); configure_stream_local("RC_CHANNELS", 0.5f); configure_stream_local("SYS_STATUS", 0.1f); configure_stream_local("VFR_HUD", 1.0f); break; default: ret = -1; break; } if (configure_single_stream && !stream_configured && strcmp(configure_single_stream, "HEARTBEAT") != 0) { // stream was not found, assume it is disabled by default return configure_stream(configure_single_stream, 0.f); } return ret; } int Mavlink::task_main(int argc, char *argv[]) { int ch; _baudrate = 57600; _datarate = 0; _mode = MAVLINK_MODE_NORMAL; bool _force_flow_control = false; #ifdef __PX4_NUTTX /* the NuttX optarg handler does not * ignore argv[0] like the POSIX handler * does, nor does it deal with non-flag * verbs well. So we remove the application * name and the verb. */ argc -= 2; argv += 2; #endif /* don't exit from getopt loop to leave getopt global variables in consistent state, * set error flag instead */ bool err_flag = false; int myoptind = 1; const char *myoptarg = nullptr; #ifdef __PX4_POSIX char *eptr; int temp_int_arg; #endif while ((ch = px4_getopt(argc, argv, "b:r:d:u:o:m:t:fwxz", &myoptind, &myoptarg)) != EOF) { switch (ch) { case 'b': _baudrate = strtoul(myoptarg, nullptr, 10); if (_baudrate < 9600 || _baudrate > 3000000) { PX4_ERR("invalid baud rate '%s'", myoptarg); err_flag = true; } break; case 'r': _datarate = strtoul(myoptarg, nullptr, 10); if (_datarate < 10 || _datarate > MAX_DATA_RATE) { PX4_ERR("invalid data rate '%s'", myoptarg); err_flag = true; } break; case 'd': _device_name = myoptarg; set_protocol(SERIAL); break; #ifdef __PX4_POSIX case 'u': temp_int_arg = strtoul(myoptarg, &eptr, 10); if (*eptr == '\0') { _network_port = temp_int_arg; set_protocol(UDP); } else { PX4_ERR("invalid data udp_port '%s'", myoptarg); err_flag = true; } break; case 'o': temp_int_arg = strtoul(myoptarg, &eptr, 10); if (*eptr == '\0') { _remote_port = temp_int_arg; set_protocol(UDP); } else { PX4_ERR("invalid remote udp_port '%s'", myoptarg); err_flag = true; } break; case 't': _src_addr.sin_family = AF_INET; if (inet_aton(myoptarg, &_src_addr.sin_addr)) { _src_addr_initialized = true; } else { PX4_ERR("invalid partner ip '%s'", myoptarg); err_flag = true; } break; #else case 'u': case 'o': case 't': PX4_ERR("UDP options not supported on this platform"); err_flag = true; break; #endif // case 'e': // mavlink_link_termination_allowed = true; // break; case 'm': if (strcmp(myoptarg, "custom") == 0) { _mode = MAVLINK_MODE_CUSTOM; } else if (strcmp(myoptarg, "camera") == 0) { // left in here for compatibility _mode = MAVLINK_MODE_ONBOARD; } else if (strcmp(myoptarg, "onboard") == 0) { _mode = MAVLINK_MODE_ONBOARD; } else if (strcmp(myoptarg, "osd") == 0) { _mode = MAVLINK_MODE_OSD; } else if (strcmp(myoptarg, "magic") == 0) { _mode = MAVLINK_MODE_MAGIC; } else if (strcmp(myoptarg, "config") == 0) { _mode = MAVLINK_MODE_CONFIG; } else if (strcmp(myoptarg, "iridium") == 0) { _mode = MAVLINK_MODE_IRIDIUM; _rstatus.type = telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_IRIDIUM; } else if (strcmp(myoptarg, "minimal") == 0) { _mode = MAVLINK_MODE_MINIMAL; } break; case 'f': _forwarding_on = true; break; case 'w': _wait_to_transmit = true; break; case 'x': _ftp_on = true; break; case 'z': _force_flow_control = true; break; default: err_flag = true; break; } } if (err_flag) { usage(); return PX4_ERROR; } if (_datarate == 0) { /* convert bits to bytes and use 1/2 of bandwidth by default */ _datarate = _baudrate / 20; } if (_datarate > MAX_DATA_RATE) { _datarate = MAX_DATA_RATE; } if (get_protocol() == SERIAL) { if (Mavlink::instance_exists(_device_name, this)) { PX4_ERR("%s already running", _device_name); return PX4_ERROR; } PX4_INFO("mode: %s, data rate: %d B/s on %s @ %dB", mavlink_mode_str(_mode), _datarate, _device_name, _baudrate); /* flush stdout in case MAVLink is about to take it over */ fflush(stdout); /* default values for arguments */ _uart_fd = mavlink_open_uart(_baudrate, _device_name, _force_flow_control); if (_uart_fd < 0 && _mode != MAVLINK_MODE_CONFIG) { PX4_ERR("could not open %s", _device_name); return PX4_ERROR; } else if (_uart_fd < 0 && _mode == MAVLINK_MODE_CONFIG) { /* the config link is optional */ return OK; } } else if (get_protocol() == UDP) { if (Mavlink::get_instance_for_network_port(_network_port) != nullptr) { PX4_ERR("port %d already occupied", _network_port); return PX4_ERROR; } PX4_INFO("mode: %s, data rate: %d B/s on udp port %hu remote port %hu", mavlink_mode_str(_mode), _datarate, _network_port, _remote_port); } /* initialize send mutex */ pthread_mutex_init(&_send_mutex, nullptr); /* if we are passing on mavlink messages, we need to prepare a buffer for this instance */ if (_forwarding_on) { /* initialize message buffer if multiplexing is on. * make space for two messages plus off-by-one space as we use the empty element * marker ring buffer approach. */ if (OK != message_buffer_init(2 * sizeof(mavlink_message_t) + 1)) { PX4_ERR("msg buf alloc fail"); return 1; } /* initialize message buffer mutex */ pthread_mutex_init(&_message_buffer_mutex, nullptr); } /* Initialize system properties */ mavlink_update_system(); MavlinkOrbSubscription *cmd_sub = add_orb_subscription(ORB_ID(vehicle_command), 0, true); MavlinkOrbSubscription *param_sub = add_orb_subscription(ORB_ID(parameter_update)); uint64_t param_time = 0; MavlinkOrbSubscription *status_sub = add_orb_subscription(ORB_ID(vehicle_status)); uint64_t status_time = 0; MavlinkOrbSubscription *ack_sub = add_orb_subscription(ORB_ID(vehicle_command_ack), 0, true); /* We don't want to miss the first advertise of an ACK, so we subscribe from the * beginning and not just when the topic exists. */ ack_sub->subscribe_from_beginning(true); cmd_sub->subscribe_from_beginning(true); /* command ack */ orb_advert_t command_ack_pub = nullptr; MavlinkOrbSubscription *mavlink_log_sub = add_orb_subscription(ORB_ID(mavlink_log)); struct vehicle_status_s status; status_sub->update(&status_time, &status); /* Activate sending the data by default (for the IRIDIUM mode it will be disabled after the first round of packages is sent)*/ _transmitting_enabled = true; _transmitting_enabled_commanded = true; if (_mode == MAVLINK_MODE_IRIDIUM) { _transmitting_enabled_commanded = false; } /* add default streams depending on mode */ if (_mode != MAVLINK_MODE_IRIDIUM) { /* HEARTBEAT is constant rate stream, rate never adjusted */ configure_stream("HEARTBEAT", 1.0f); /* STATUSTEXT stream is like normal stream but gets messages from logbuffer instead of uORB */ configure_stream("STATUSTEXT", 20.0f); /* COMMAND_LONG stream: use unlimited rate to send all commands */ configure_stream("COMMAND_LONG"); } if (configure_streams_to_default() != 0) { PX4_ERR("configure_streams_to_default() failed"); } /* set main loop delay depending on data rate to minimize CPU overhead */ _main_loop_delay = (MAIN_LOOP_DELAY * 1000) / _datarate; /* hard limit to 1000 Hz at max */ if (_main_loop_delay < MAVLINK_MIN_INTERVAL) { _main_loop_delay = MAVLINK_MIN_INTERVAL; } /* hard limit to 100 Hz at least */ if (_main_loop_delay > MAVLINK_MAX_INTERVAL) { _main_loop_delay = MAVLINK_MAX_INTERVAL; } /* now the instance is fully initialized and we can bump the instance count */ LL_APPEND(_mavlink_instances, this); /* init socket if necessary */ if (get_protocol() == UDP) { init_udp(); } /* if the protocol is serial, we send the system version blindly */ if (get_protocol() == SERIAL) { send_autopilot_capabilites(); } /* start the MAVLink receiver last to avoid a race */ MavlinkReceiver::receive_start(&_receive_thread, this); while (!_task_should_exit) { /* main loop */ usleep(_main_loop_delay); perf_begin(_loop_perf); hrt_abstime t = hrt_absolute_time(); update_rate_mult(); if (param_sub->update(&param_time, nullptr)) { /* parameters updated */ mavlink_update_system(); } check_radio_config(); if (status_sub->update(&status_time, &status)) { /* switch HIL mode if required */ set_hil_enabled(status.hil_state == vehicle_status_s::HIL_STATE_ON); set_manual_input_mode_generation(status.rc_input_mode == vehicle_status_s::RC_IN_MODE_GENERATED); if (_mode == MAVLINK_MODE_IRIDIUM) { if (_transmitting_enabled && !status.high_latency_data_link_active && !_transmitting_enabled_commanded && (_first_heartbeat_sent)) { _transmitting_enabled = false; mavlink_and_console_log_info(&_mavlink_log_pub, "Disable transmitting with IRIDIUM mavlink on device %s", _device_name); } else if (!_transmitting_enabled && status.high_latency_data_link_active) { _transmitting_enabled = true; mavlink_and_console_log_info(&_mavlink_log_pub, "Enable transmitting with IRIDIUM mavlink on device %s", _device_name); } } } struct vehicle_command_s vehicle_cmd; if (cmd_sub->update_if_changed(&vehicle_cmd)) { if ((vehicle_cmd.command == vehicle_command_s::VEHICLE_CMD_CONTROL_HIGH_LATENCY) && (_mode == MAVLINK_MODE_IRIDIUM)) { if (vehicle_cmd.param1 > 0.5f) { if (!_transmitting_enabled) { mavlink_and_console_log_info(&_mavlink_log_pub, "Enable transmitting with IRIDIUM mavlink on device %s by command", _device_name); } _transmitting_enabled = true; _transmitting_enabled_commanded = true; } else { if (_transmitting_enabled) { mavlink_and_console_log_info(&_mavlink_log_pub, "Disable transmitting with IRIDIUM mavlink on device %s by command", _device_name); } _transmitting_enabled = false; _transmitting_enabled_commanded = false; } // send positive command ack vehicle_command_ack_s command_ack = {}; command_ack.timestamp = vehicle_cmd.timestamp; command_ack.command = vehicle_cmd.command; command_ack.result = vehicle_command_ack_s::VEHICLE_RESULT_ACCEPTED; command_ack.from_external = !vehicle_cmd.from_external; command_ack.target_system = vehicle_cmd.source_system; command_ack.target_component = vehicle_cmd.source_component; if (command_ack_pub != nullptr) { orb_publish(ORB_ID(vehicle_command_ack), command_ack_pub, &command_ack); } else { command_ack_pub = orb_advertise_queue(ORB_ID(vehicle_command_ack), &command_ack, vehicle_command_ack_s::ORB_QUEUE_LENGTH); } } } /* send command ACK */ uint16_t current_command_ack = 0; struct vehicle_command_ack_s command_ack; if (ack_sub->update_if_changed(&command_ack)) { if (!command_ack.from_external) { mavlink_command_ack_t msg; msg.result = command_ack.result; msg.command = command_ack.command; msg.progress = command_ack.result_param1; msg.result_param2 = command_ack.result_param2; msg.target_system = command_ack.target_system; msg.target_component = command_ack.target_component; current_command_ack = command_ack.command; // TODO: always transmit the acknowledge once it is only sent over the instance the command is received //bool _transmitting_enabled_temp = _transmitting_enabled; //_transmitting_enabled = true; mavlink_msg_command_ack_send_struct(get_channel(), &msg); //_transmitting_enabled = _transmitting_enabled_temp; } } struct mavlink_log_s mavlink_log; if (mavlink_log_sub->update_if_changed(&mavlink_log)) { _logbuffer.put(&mavlink_log); } /* check for shell output */ if (_mavlink_shell && _mavlink_shell->available() > 0) { if (get_free_tx_buf() >= MAVLINK_MSG_ID_SERIAL_CONTROL_LEN + MAVLINK_NUM_NON_PAYLOAD_BYTES) { mavlink_serial_control_t msg; msg.baudrate = 0; msg.flags = SERIAL_CONTROL_FLAG_REPLY; msg.timeout = 0; msg.device = SERIAL_CONTROL_DEV_SHELL; msg.count = _mavlink_shell->read(msg.data, sizeof(msg.data)); mavlink_msg_serial_control_send_struct(get_channel(), &msg); } } /* check for ulog streaming messages */ if (_mavlink_ulog) { if (_mavlink_ulog_stop_requested) { _mavlink_ulog->stop(); _mavlink_ulog = nullptr; _mavlink_ulog_stop_requested = false; } else { if (current_command_ack == vehicle_command_s::VEHICLE_CMD_LOGGING_START) { _mavlink_ulog->start_ack_received(); } int ret = _mavlink_ulog->handle_update(get_channel()); if (ret < 0) { //abort the streaming on error if (ret != -1) { PX4_WARN("mavlink ulog stream update failed, stopping (%i)", ret); } _mavlink_ulog->stop(); _mavlink_ulog = nullptr; } } } /* check for requested subscriptions */ if (_subscribe_to_stream != nullptr) { if (_subscribe_to_stream_rate < -1.5f) { if (configure_streams_to_default(_subscribe_to_stream) == 0) { if (get_protocol() == SERIAL) { PX4_DEBUG("stream %s on device %s set to default rate", _subscribe_to_stream, _device_name); } else if (get_protocol() == UDP) { PX4_DEBUG("stream %s on UDP port %d set to default rate", _subscribe_to_stream, _network_port); } } else { PX4_ERR("setting stream %s to default failed", _subscribe_to_stream); } } else if (configure_stream(_subscribe_to_stream, _subscribe_to_stream_rate) == 0) { if (fabsf(_subscribe_to_stream_rate) > 0.00001f) { if (get_protocol() == SERIAL) { PX4_DEBUG("stream %s on device %s enabled with rate %.1f Hz", _subscribe_to_stream, _device_name, (double)_subscribe_to_stream_rate); } else if (get_protocol() == UDP) { PX4_DEBUG("stream %s on UDP port %d enabled with rate %.1f Hz", _subscribe_to_stream, _network_port, (double)_subscribe_to_stream_rate); } } else { if (get_protocol() == SERIAL) { PX4_DEBUG("stream %s on device %s disabled", _subscribe_to_stream, _device_name); } else if (get_protocol() == UDP) { PX4_DEBUG("stream %s on UDP port %d disabled", _subscribe_to_stream, _network_port); } } } else { if (get_protocol() == SERIAL) { PX4_ERR("stream %s on device %s not found", _subscribe_to_stream, _device_name); } else if (get_protocol() == UDP) { PX4_ERR("stream %s on UDP port %d not found", _subscribe_to_stream, _network_port); } } _subscribe_to_stream = nullptr; } /* update streams */ MavlinkStream *stream; LL_FOREACH(_streams, stream) { stream->update(t); if (!_first_heartbeat_sent) { if (_mode == MAVLINK_MODE_IRIDIUM) { if (stream->get_id() == MAVLINK_MSG_ID_HIGH_LATENCY2) { _first_heartbeat_sent = stream->first_message_sent(); } } else { if (stream->get_id() == MAVLINK_MSG_ID_HEARTBEAT) { _first_heartbeat_sent = stream->first_message_sent(); } } } } /* pass messages from other UARTs */ if (_forwarding_on) { bool is_part; uint8_t *read_ptr; uint8_t *write_ptr; pthread_mutex_lock(&_message_buffer_mutex); int available = message_buffer_get_ptr((void **)&read_ptr, &is_part); pthread_mutex_unlock(&_message_buffer_mutex); if (available > 0) { // Reconstruct message from buffer mavlink_message_t msg; write_ptr = (uint8_t *)&msg; // Pull a single message from the buffer size_t read_count = available; if (read_count > sizeof(mavlink_message_t)) { read_count = sizeof(mavlink_message_t); } memcpy(write_ptr, read_ptr, read_count); // We hold the mutex until after we complete the second part of the buffer. If we don't // we may end up breaking the empty slot overflow detection semantics when we mark the // possibly partial read below. pthread_mutex_lock(&_message_buffer_mutex); message_buffer_mark_read(read_count); /* write second part of buffer if there is some */ if (is_part && read_count < sizeof(mavlink_message_t)) { write_ptr += read_count; available = message_buffer_get_ptr((void **)&read_ptr, &is_part); read_count = sizeof(mavlink_message_t) - read_count; memcpy(write_ptr, read_ptr, read_count); message_buffer_mark_read(available); } pthread_mutex_unlock(&_message_buffer_mutex); resend_message(&msg); } } /* update TX/RX rates*/ if (t > _bytes_timestamp + 1000000) { if (_bytes_timestamp != 0) { float dt = (t - _bytes_timestamp) / 1000.0f; _rate_tx = _bytes_tx / dt; _rate_txerr = _bytes_txerr / dt; _rate_rx = _bytes_rx / dt; _bytes_tx = 0; _bytes_txerr = 0; _bytes_rx = 0; } _bytes_timestamp = t; } perf_end(_loop_perf); /* confirm task running only once fully initialized */ _task_running = true; } /* first wait for threads to complete before tearing down anything */ pthread_join(_receive_thread, nullptr); delete _subscribe_to_stream; _subscribe_to_stream = nullptr; /* delete streams */ MavlinkStream *stream_to_del = nullptr; MavlinkStream *stream_next = _streams; while (stream_next != nullptr) { stream_to_del = stream_next; stream_next = stream_to_del->next; delete stream_to_del; } _streams = nullptr; /* delete subscriptions */ MavlinkOrbSubscription *sub_to_del = nullptr; MavlinkOrbSubscription *sub_next = _subscriptions; while (sub_next != nullptr) { sub_to_del = sub_next; sub_next = sub_to_del->next; delete sub_to_del; } _subscriptions = nullptr; if (_uart_fd >= 0 && !_is_usb_uart) { /* close UART */ ::close(_uart_fd); } if (_socket_fd >= 0) { close(_socket_fd); _socket_fd = -1; } if (_forwarding_on) { message_buffer_destroy(); pthread_mutex_destroy(&_message_buffer_mutex); } if (_mavlink_ulog) { _mavlink_ulog->stop(); _mavlink_ulog = nullptr; } PX4_INFO("exiting channel %i", (int)_channel); return OK; } void Mavlink::check_radio_config() { /* radio config check */ if (_uart_fd >= 0 && _radio_id != 0 && _rstatus.type == telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_3DR_RADIO) { /* request to configure radio and radio is present */ FILE *fs = fdopen(_uart_fd, "w"); if (fs) { /* switch to AT command mode */ usleep(1200000); fprintf(fs, "+++\n"); usleep(1200000); if (_radio_id > 0) { /* set channel */ fprintf(fs, "ATS3=%u\n", _radio_id); usleep(200000); } else { /* reset to factory defaults */ fprintf(fs, "AT&F\n"); usleep(200000); } /* write config */ fprintf(fs, "AT&W"); usleep(200000); /* reboot */ fprintf(fs, "ATZ"); usleep(200000); // XXX NuttX suffers from a bug where // fclose() also closes the fd, not just // the file stream. Since this is a one-time // config thing, we leave the file struct // allocated. #ifndef __PX4_NUTTX fclose(fs); #endif } else { PX4_WARN("open fd %d failed", _uart_fd); } /* reset param and save */ _radio_id = 0; param_set_no_notification(_param_radio_id, &_radio_id); } } int Mavlink::start_helper(int argc, char *argv[]) { /* create the instance in task context */ Mavlink *instance = new Mavlink(); int res; if (!instance) { /* out of memory */ res = -ENOMEM; PX4_ERR("OUT OF MEM"); } else { /* this will actually only return once MAVLink exits */ res = instance->task_main(argc, argv); instance->_task_running = false; } return res; } int Mavlink::start(int argc, char *argv[]) { MavlinkULog::initialize(); MavlinkCommandSender::initialize(); // Wait for the instance count to go up one // before returning to the shell int ic = Mavlink::instance_count(); if (ic == Mavlink::MAVLINK_MAX_INSTANCES) { PX4_ERR("Maximum MAVLink instance count of %d reached.", (int)Mavlink::MAVLINK_MAX_INSTANCES); return 1; } // Instantiate thread char buf[24]; sprintf(buf, "mavlink_if%d", ic); // This is where the control flow splits // between the starting task and the spawned // task - start_helper() only returns // when the started task exits. px4_task_spawn_cmd(buf, SCHED_DEFAULT, SCHED_PRIORITY_DEFAULT, 2650, (px4_main_t)&Mavlink::start_helper, (char *const *)argv); // Ensure that this shell command // does not return before the instance // is fully initialized. As this is also // the only path to create a new instance, // this is effectively a lock on concurrent // instance starting. XXX do a real lock. // Sleep 500 us between each attempt const unsigned sleeptime = 500; // Wait 100 ms max for the startup. const unsigned limit = 100 * 1000 / sleeptime; unsigned count = 0; while (ic == Mavlink::instance_count() && count < limit) { ::usleep(sleeptime); count++; } if (ic == Mavlink::instance_count()) { return PX4_ERROR; } else { return PX4_OK; } } void Mavlink::display_status() { if (_rstatus.heartbeat_time > 0) { printf("\tGCS heartbeat:\t%llu us ago\n", (unsigned long long)hrt_elapsed_time(&_rstatus.heartbeat_time)); } printf("\tmavlink chan: #%u\n", _channel); if (_rstatus.timestamp > 0) { printf("\ttype:\t\t"); switch (_rstatus.type) { case telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_3DR_RADIO: printf("3DR RADIO\n"); printf("\trssi:\t\t%d\n", _rstatus.rssi); printf("\tremote rssi:\t%u\n", _rstatus.remote_rssi); printf("\ttxbuf:\t\t%u\n", _rstatus.txbuf); printf("\tnoise:\t\t%d\n", _rstatus.noise); printf("\tremote noise:\t%u\n", _rstatus.remote_noise); printf("\trx errors:\t%u\n", _rstatus.rxerrors); printf("\tfixed:\t\t%u\n", _rstatus.fixed); break; case telemetry_status_s::TELEMETRY_STATUS_RADIO_TYPE_USB: printf("USB CDC\n"); break; default: printf("GENERIC LINK OR RADIO\n"); break; } } else { printf("\tno telem status.\n"); } printf("\tflow control: %s\n", _flow_control_mode ? "ON" : "OFF"); printf("\trates:\n"); printf("\t tx: %.3f kB/s\n", (double)_rate_tx); printf("\t txerr: %.3f kB/s\n", (double)_rate_txerr); printf("\t tx rate mult: %.3f\n", (double)_rate_mult); printf("\t tx rate max: %i B/s\n", _datarate); printf("\t rx: %.3f kB/s\n", (double)_rate_rx); if (_mavlink_ulog) { printf("\tULog rate: %.1f%% of max %.1f%%\n", (double)_mavlink_ulog->current_data_rate() * 100., (double)_mavlink_ulog->maximum_data_rate() * 100.); } printf("\taccepting commands: %s, FTP enabled: %s, TX enabled: %s\n", accepting_commands() ? "YES" : "NO", _ftp_on ? "YES" : "NO", _transmitting_enabled ? "YES" : "NO"); printf("\tmode: %s\n", mavlink_mode_str(_mode)); printf("\tMAVLink version: %i\n", _protocol_version); printf("\ttransport protocol: "); switch (_protocol) { case UDP: printf("UDP (%i, remote port: %i)\n", _network_port, _remote_port); #ifdef __PX4_POSIX if (get_client_source_initialized()) { printf("\tpartner IP: %s\n", inet_ntoa(get_client_source_address().sin_addr)); } #endif break; case TCP: printf("TCP\n"); break; case SERIAL: printf("serial (%s @%i)\n", _device_name, _baudrate); break; } if (_ping_stats.last_ping_time > 0) { printf("\tping statistics:\n"); printf("\t last: %0.2f ms\n", (double)_ping_stats.last_rtt); printf("\t mean: %0.2f ms\n", (double)_ping_stats.mean_rtt); printf("\t max: %0.2f ms\n", (double)_ping_stats.max_rtt); printf("\t min: %0.2f ms\n", (double)_ping_stats.min_rtt); printf("\t dropped packets: %u\n", _ping_stats.dropped_packets); } } void Mavlink::display_status_streams() { printf("\t%-20s%-16s %s\n", "Name", "Rate Config (current) [Hz]", "Message Size (if active) [B]"); const float rate_mult = _rate_mult; MavlinkStream *stream; LL_FOREACH(_streams, stream) { const int interval = stream->get_interval(); const unsigned size = stream->get_size(); char rate_str[20]; if (interval < 0) { strcpy(rate_str, "unlimited"); } else { float rate = 1000000.0f / (float)interval; // Note that the actual current rate can be lower if the associated uORB topic updates at a // lower rate. float rate_current = stream->const_rate() ? rate : rate * rate_mult; snprintf(rate_str, sizeof(rate_str), "%6.2f (%.3f)", (double)rate, (double)rate_current); } printf("\t%-30s%-16s", stream->get_name(), rate_str); if (size > 0) { printf(" %3i\n", size); } else { printf("\n"); } } } int Mavlink::stream_command(int argc, char *argv[]) { const char *device_name = DEFAULT_DEVICE_NAME; float rate = -1.0f; const char *stream_name = nullptr; unsigned short network_port = 0; char *eptr; int temp_int_arg; bool provided_device = false; bool provided_network_port = false; /* * Called via main with original argv * mavlink start * * Remove 2 */ argc -= 2; argv += 2; /* don't exit from getopt loop to leave getopt global variables in consistent state, * set error flag instead */ bool err_flag = false; int i = 0; while (i < argc) { if (0 == strcmp(argv[i], "-r") && i < argc - 1) { rate = strtod(argv[i + 1], nullptr); if (rate < 0.0f) { err_flag = true; } i++; } else if (0 == strcmp(argv[i], "-d") && i < argc - 1) { provided_device = true; device_name = argv[i + 1]; i++; } else if (0 == strcmp(argv[i], "-s") && i < argc - 1) { stream_name = argv[i + 1]; i++; } else if (0 == strcmp(argv[i], "-u") && i < argc - 1) { provided_network_port = true; temp_int_arg = strtoul(argv[i + 1], &eptr, 10); if (*eptr == '\0') { network_port = temp_int_arg; } else { err_flag = true; } i++; } else { err_flag = true; } i++; } if (!err_flag && stream_name != nullptr) { Mavlink *inst = nullptr; if (provided_device && !provided_network_port) { inst = get_instance_for_device(device_name); } else if (provided_network_port && !provided_device) { inst = get_instance_for_network_port(network_port); } else if (provided_device && provided_network_port) { PX4_WARN("please provide either a device name or a network port"); return 1; } if (rate < 0.f) { rate = -2.f; // use default rate } if (inst != nullptr) { inst->configure_stream_threadsafe(stream_name, rate); } else { // If the link is not running we should complain, but not fall over // because this is so easy to get wrong and not fatal. Warning is sufficient. if (provided_device) { PX4_WARN("mavlink for device %s is not running", device_name); } else { PX4_WARN("mavlink for network on port %hu is not running", network_port); } return 1; } } else { usage(); return 1; } return OK; } void Mavlink::set_boot_complete() { _boot_complete = true; #ifdef __PX4_POSIX Mavlink *inst; LL_FOREACH(::_mavlink_instances, inst) { if ((inst->get_mode() != MAVLINK_MODE_ONBOARD) && (!inst->broadcast_enabled()) && ((inst->get_protocol() == UDP) || (inst->get_protocol() == TCP))) { PX4_INFO("MAVLink only on localhost (set param MAV_BROADCAST = 1 to enable network)"); } } #endif } static void usage() { PRINT_MODULE_DESCRIPTION( R"DESCR_STR( ### Description This module implements the MAVLink protocol, which can be used on a Serial link or UDP network connection. It communicates with the system via uORB: some messages are directly handled in the module (eg. mission protocol), others are published via uORB (eg. vehicle_command). Streams are used to send periodic messages with a specific rate, such as the vehicle attitude. When starting the mavlink instance, a mode can be specified, which defines the set of enabled streams with their rates. For a running instance, streams can be configured via `mavlink stream` command. There can be multiple independent instances of the module, each connected to one serial device or network port. ### Implementation The implementation uses 2 threads, a sending and a receiving thread. The sender runs at a fixed rate and dynamically reduces the rates of the streams if the combined bandwidth is higher than the configured rate (`-r`) or the physical link becomes saturated. This can be checked with `mavlink status`, see if `rate mult` is less than 1. **Careful**: some of the data is accessed and modified from both threads, so when changing code or extend the functionality, this needs to be take into account, in order to avoid race conditions and corrupt data. ### Examples Start mavlink on ttyS1 serial with baudrate 921600 and maximum sending rate of 80kB/s: $ mavlink start -d /dev/ttyS1 -b 921600 -m onboard -r 80000 Start mavlink on UDP port 14556 and enable the HIGHRES_IMU message with 50Hz: $ mavlink start -u 14556 -r 1000000 $ mavlink stream -u 14556 -s HIGHRES_IMU -r 50 )DESCR_STR"); PRINT_MODULE_USAGE_NAME("mavlink", "communication"); PRINT_MODULE_USAGE_COMMAND_DESCR("start", "Start a new instance"); PRINT_MODULE_USAGE_PARAM_STRING('d', "/dev/ttyS1", "<file:dev>", "Select Serial Device", true); PRINT_MODULE_USAGE_PARAM_INT('b', 57600, 9600, 3000000, "Baudrate", true); PRINT_MODULE_USAGE_PARAM_INT('r', 0, 10, 10000000, "Maximum sending data rate in B/s (if 0, use baudrate / 20)", true); #ifdef __PX4_POSIX PRINT_MODULE_USAGE_PARAM_INT('u', 14556, 0, 65536, "Select UDP Network Port (local)", true); PRINT_MODULE_USAGE_PARAM_INT('o', 14550, 0, 65536, "Select UDP Network Port (remote)", true); PRINT_MODULE_USAGE_PARAM_STRING('t', "127.0.0.1", nullptr, "Partner IP (broadcasting can be enabled via MAV_BROADCAST param)", true); #endif PRINT_MODULE_USAGE_PARAM_STRING('m', "normal", "custom|camera|onboard|osd|magic|config|iridium|minimal", "Mode: sets default streams and rates", true); PRINT_MODULE_USAGE_PARAM_FLAG('f', "Enable message forwarding to other Mavlink instances", true); PRINT_MODULE_USAGE_PARAM_FLAG('w', "Wait to send, until first message received", true); PRINT_MODULE_USAGE_PARAM_FLAG('x', "Enable FTP", true); PRINT_MODULE_USAGE_PARAM_FLAG('z', "Force flow control always on", true); PRINT_MODULE_USAGE_COMMAND_DESCR("stop-all", "Stop all instances"); PRINT_MODULE_USAGE_COMMAND_DESCR("status", "Print status for all instances"); PRINT_MODULE_USAGE_ARG("streams", "Print all enabled streams", true); PRINT_MODULE_USAGE_COMMAND_DESCR("stream", "Configure the sending rate of a stream for a running instance"); #ifdef __PX4_POSIX PRINT_MODULE_USAGE_PARAM_INT('u', 0, 0, 65536, "Select Mavlink instance via local Network Port", true); #endif PRINT_MODULE_USAGE_PARAM_STRING('d', nullptr, "<file:dev>", "Select Mavlink instance via Serial Device", true); PRINT_MODULE_USAGE_PARAM_STRING('s', nullptr, nullptr, "Mavlink stream to configure", false); PRINT_MODULE_USAGE_PARAM_FLOAT('r', -1.f, 0.f, 2000.f, "Rate in Hz (0 = turn off, -1 = set to default)", false); PRINT_MODULE_USAGE_COMMAND_DESCR("boot_complete", "Enable sending of messages. (Must be) called as last step in startup script."); } int mavlink_main(int argc, char *argv[]) { if (argc < 2) { usage(); return 1; } if (!strcmp(argv[1], "start")) { return Mavlink::start(argc, argv); } else if (!strcmp(argv[1], "stop")) { PX4_WARN("mavlink stop is deprecated, use stop-all instead"); usage(); return 1; } else if (!strcmp(argv[1], "stop-all")) { return Mavlink::destroy_all_instances(); } else if (!strcmp(argv[1], "status")) { bool show_streams_status = argc > 2 && strcmp(argv[2], "streams") == 0; return Mavlink::get_status_all_instances(show_streams_status); } else if (!strcmp(argv[1], "stream")) { return Mavlink::stream_command(argc, argv); } else if (!strcmp(argv[1], "boot_complete")) { Mavlink::set_boot_complete(); return 0; } else { usage(); return 1; } return 0; }
; A033567: a(n) = (2*n-1)*(4*n-1). ; 1,3,21,55,105,171,253,351,465,595,741,903,1081,1275,1485,1711,1953,2211,2485,2775,3081,3403,3741,4095,4465,4851,5253,5671,6105,6555,7021,7503,8001,8515,9045,9591,10153,10731,11325,11935,12561,13203,13861,14535,15225,15931,16653,17391,18145,18915,19701,20503,21321,22155,23005,23871,24753,25651,26565,27495,28441,29403,30381,31375,32385,33411,34453,35511,36585,37675,38781,39903,41041,42195,43365,44551,45753,46971,48205,49455,50721,52003,53301,54615,55945,57291,58653,60031,61425,62835,64261,65703,67161,68635,70125,71631,73153,74691,76245,77815 mov $1,4 mul $1,$0 sub $1,1 bin $1,2 mov $0,$1
.global s_prepare_buffers s_prepare_buffers: push %r11 push %r14 push %r15 push %r9 push %rbx push %rcx push %rdi push %rdx push %rsi lea addresses_WT_ht+0xc480, %r15 nop nop nop cmp %rdx, %rdx mov $0x6162636465666768, %r14 movq %r14, %xmm1 vmovups %ymm1, (%r15) nop sub %rcx, %rcx lea addresses_UC_ht+0x1b9c0, %r11 nop and $38406, %rbx mov (%r11), %dx nop sub %rbx, %rbx lea addresses_normal_ht+0x480, %r14 nop nop sub %r9, %r9 mov (%r14), %edx nop nop nop nop nop xor %r14, %r14 lea addresses_D_ht+0x9840, %rdx nop nop nop and %r15, %r15 mov (%rdx), %r11w nop dec %r11 lea addresses_D_ht+0x143b0, %r11 nop nop nop add $37648, %r14 mov (%r11), %cx nop nop nop nop nop and %r11, %r11 lea addresses_A_ht+0x11a5a, %r9 clflush (%r9) nop nop nop cmp $13655, %r11 movl $0x61626364, (%r9) nop nop nop nop cmp $65143, %r9 lea addresses_normal_ht+0x8e00, %rsi lea addresses_A_ht+0x9e80, %rdi nop nop nop nop nop xor %r15, %r15 mov $54, %rcx rep movsq nop nop nop nop nop add %rdi, %rdi lea addresses_A_ht+0x31c0, %r14 inc %rbx mov $0x6162636465666768, %r15 movq %r15, %xmm4 movups %xmm4, (%r14) nop nop nop nop nop inc %rdi lea addresses_D_ht+0x1cd80, %rsi lea addresses_D_ht+0x15368, %rdi nop nop nop nop nop dec %r11 mov $6, %rcx rep movsq nop cmp $6661, %rdx lea addresses_normal_ht+0x69f0, %rsi lea addresses_D_ht+0x6548, %rdi nop nop nop xor %r14, %r14 mov $15, %rcx rep movsb nop nop xor $28898, %r11 lea addresses_UC_ht+0x165a0, %r14 nop nop nop nop xor $30866, %rdi movl $0x61626364, (%r14) nop xor %rdi, %rdi lea addresses_normal_ht+0x19788, %rsi lea addresses_D_ht+0x1e780, %rdi nop nop nop and %rdx, %rdx mov $100, %rcx rep movsq nop nop nop nop nop cmp $41536, %r11 lea addresses_WT_ht+0xac80, %r9 clflush (%r9) nop nop nop nop lfence movups (%r9), %xmm6 vpextrq $0, %xmm6, %r14 nop nop nop nop add %rdi, %rdi lea addresses_A_ht+0xadf0, %r14 nop nop nop sub %rdx, %rdx movups (%r14), %xmm1 vpextrq $1, %xmm1, %r11 nop nop nop and $35640, %rcx lea addresses_normal_ht+0x1a080, %rbx nop nop nop nop sub %rcx, %rcx movl $0x61626364, (%rbx) nop nop nop nop nop sub %r14, %r14 pop %rsi pop %rdx pop %rdi pop %rcx pop %rbx pop %r9 pop %r15 pop %r14 pop %r11 ret .global s_faulty_load s_faulty_load: push %r10 push %r13 push %r14 push %r8 push %rbp push %rcx push %rdi // Load mov $0x7a0, %rbp nop nop nop nop cmp $37393, %rdi mov (%rbp), %r13d nop and $46831, %rbp // Store lea addresses_WC+0x1f468, %r10 nop and %r13, %r13 movw $0x5152, (%r10) nop nop xor $36811, %rcx // Store mov $0x3ac8840000000c00, %r10 nop inc %r8 movl $0x51525354, (%r10) nop sub %r13, %r13 // Store lea addresses_PSE+0x5a68, %rcx nop nop nop nop nop and %rdi, %rdi mov $0x5152535455565758, %r8 movq %r8, (%rcx) nop nop nop and $30526, %rbp // Store lea addresses_US+0x8080, %r10 clflush (%r10) cmp %r14, %r14 movb $0x51, (%r10) nop and %r8, %r8 // Store lea addresses_UC+0x1d264, %r14 nop nop nop nop nop xor %r8, %r8 mov $0x5152535455565758, %rcx movq %rcx, %xmm7 movups %xmm7, (%r14) nop nop nop nop and $61796, %rbp // Store lea addresses_US+0x8080, %rdi nop nop nop cmp $7788, %r8 mov $0x5152535455565758, %rcx movq %rcx, %xmm2 movups %xmm2, (%rdi) nop add $50303, %rbp // Store lea addresses_US+0x9cd4, %r13 nop xor $17454, %rdi mov $0x5152535455565758, %rcx movq %rcx, %xmm4 movups %xmm4, (%r13) nop nop nop nop nop xor %rbp, %rbp // Store lea addresses_US+0x132c0, %r8 sub %rbp, %rbp movl $0x51525354, (%r8) nop nop nop add $51097, %r8 // Faulty Load lea addresses_US+0x8080, %rbp nop sub %r13, %r13 mov (%rbp), %cx lea oracles, %rdi and $0xff, %rcx shlq $12, %rcx mov (%rdi,%rcx,1), %rcx pop %rdi pop %rcx pop %rbp pop %r8 pop %r14 pop %r13 pop %r10 ret /* <gen_faulty_load> [REF] {'src': {'congruent': 0, 'AVXalign': True, 'same': False, 'size': 32, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} {'src': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_P'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_WC'}} {'OP': 'STOR', 'dst': {'congruent': 1, 'AVXalign': True, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_NC'}} {'OP': 'STOR', 'dst': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 8, 'NT': True, 'type': 'addresses_PSE'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 1, 'NT': False, 'type': 'addresses_US'}} {'OP': 'STOR', 'dst': {'congruent': 2, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_UC'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_US'}} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_US'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_US'}} [Faulty Load] {'src': {'congruent': 0, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_US'}, 'OP': 'LOAD'} <gen_prepare_buffer> {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': True, 'size': 32, 'NT': False, 'type': 'addresses_WT_ht'}} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 2, 'NT': False, 'type': 'addresses_UC_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 9, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 5, 'AVXalign': False, 'same': True, 'size': 2, 'NT': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 4, 'AVXalign': False, 'same': False, 'size': 2, 'NT': True, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 0, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 9, 'same': False, 'type': 'addresses_A_ht'}} {'OP': 'STOR', 'dst': {'congruent': 6, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}} {'src': {'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'REPM', 'dst': {'congruent': 2, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 4, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 3, 'same': False, 'type': 'addresses_D_ht'}} {'OP': 'STOR', 'dst': {'congruent': 5, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_UC_ht'}} {'src': {'congruent': 1, 'same': False, 'type': 'addresses_normal_ht'}, 'OP': 'REPM', 'dst': {'congruent': 8, 'same': False, 'type': 'addresses_D_ht'}} {'src': {'congruent': 10, 'AVXalign': False, 'same': True, 'size': 16, 'NT': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'} {'src': {'congruent': 3, 'AVXalign': False, 'same': False, 'size': 16, 'NT': False, 'type': 'addresses_A_ht'}, 'OP': 'LOAD'} {'OP': 'STOR', 'dst': {'congruent': 10, 'AVXalign': False, 'same': False, 'size': 4, 'NT': False, 'type': 'addresses_normal_ht'}} {'00': 57, '58': 21772} 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 58 00 58 58 58 58 58 58 58 */
.intel_syntax noprefix MFENCE MOV rax, [r14] MOV rax, [r14 + 4096] MOV rax, [r14 + 8192] MOV rax, [r14 + 12288] MOV rax, [r14 + 16384] MOV rax, [r14 + 20480] MOV rax, [r14 + 24576] MOV rax, [r14 + 28672] MOV rax, [r14 + 32768] MOV rax, [r14 + 512] MOV rax, [r14 + 512 + 4096] MOV rax, [r14 + 512 + 8192] MOV rax, [r14 + 512 + 12288] MOV rax, [r14 + 512 + 16384] MOV rax, [r14 + 512 + 20480] MOV rax, [r14 + 512 + 24576] MOV rax, [r14 + 512 + 28672] MOV rax, [r14 + 512 + 32768] MOV rax, [r14 + 1024] MOV rax, [r14 + 1024 + 4096] MOV rax, [r14 + 1024 + 8192] MOV rax, [r14 + 1024 + 12288] MOV rax, [r14 + 1024 + 16384] MOV rax, [r14 + 1024 + 20480] MOV rax, [r14 + 1024 + 24576] MOV rax, [r14 + 1024 + 28672] MOV rax, [r14 + 1024 + 32768] MOV rax, [r14 + 2048] MOV rax, [r14 + 2048 + 4096] MOV rax, [r14 + 2048 + 8192] MOV rax, [r14 + 2048 + 12288] MOV rax, [r14 + 2048 + 16384] MOV rax, [r14 + 2048 + 20480] MOV rax, [r14 + 2048 + 24576] MOV rax, [r14 + 2048 + 28672] MOV rax, [r14 + 2048 + 32768] MFENCE
; A182619: Number of vertices that are connected to two edges in a spiral without holes constructed with n hexagons. ; 6,8,9,10,11,12,12,13,14,14,15,15,16,16,17,17,18,18,18,19,19,20,20,20,21,21,21,22,22,22,23,23,23,24,24,24,24 mov $2,$0 add $2,$0 mul $0,4 mul $2,4 add $2,4 add $0,$2 lpb $0 sub $0,3 add $1,1 add $0,$1 sub $0,$1 sub $0,$1 trn $0,$1 lpe add $1,5
; void zx_scroll_up_attr(uchar rows, uchar attr) SECTION code_clib SECTION code_arch PUBLIC zx_scroll_up_attr EXTERN asm0_zx_scroll_up_attr zx_scroll_up_attr: pop af pop hl pop de push de push hl push af jp asm0_zx_scroll_up_attr
/* Copyright (c) 2015 Microsoft Corporation. All rights reserved. Released under Apache 2.0 license as described in the file LICENSE. Author: Leonardo de Moura */ #include <vector> #include "util/test.h" #include "shell/lean_js.h" using namespace lean; int main() { save_stack_info(); initialize_emscripten(); emscripten_import_module("standard"); int r = emscripten_process_file("file1.lean"); if (r != 0) return r; r = emscripten_process_file("file2.lean"); if (r != 0) return r; r = has_violations() ? 1 : 0; finalize_emscripten(); return r; }
#include "ModelEncoder.h" #include <regex> namespace Ingenuity { ModelEncoder::Loader::~Loader() { for(unsigned i = 0; i < models.size(); ++i) { delete models[i].mesh; } } void ModelEncoder::Loader::Respond() { if(buffer) { models = DecodeModels(buffer, bufferLength); int directoryIndex = path.find_last_of(L"\\/"); std::wstring subDirPath = path.substr(0, directoryIndex + 1); subDirPath = std::regex_replace(subDirPath, std::wregex(L"\\b\\/"), L"//"); subDir = files->GetSubDirectory(directory, subDirPath.c_str()); if(!subDir) subDir = directory; AssetBatch batch; for(unsigned i = 0; i < models.size(); ++i) { if(*models[i].diffuseTexturePath) { batch.emplace_back(subDir, models[i].diffuseTexturePath, TextureAsset); } if(*models[i].normalTexturePath) { batch.emplace_back(subDir, models[i].normalTexturePath, TextureAsset); } if(*models[i].cubeTexturePath) { batch.emplace_back(subDir, models[i].cubeTexturePath, CubeMapAsset); } } if(batch.size() > 0) { texTicket = assets->Load(batch); } } } bool ModelEncoder::Loader::IsAssetReady() { if(Files::Response::complete && (texTicket == -1 || assets->IsLoaded(texTicket))) { if(!asset) { Gpu::ComplexModel * gpuModel = new Gpu::ComplexModel(models.size()); for(unsigned i = 0; i < models.size(); ++i) { gpuModel->models[i].boundingSphere = GeoBuilder().GenerateBoundingSphere(models[i].mesh->vertexBuffer); gpuModel->models[i].mesh = models[i].mesh->ToGpuMesh(gpu); gpuModel->models[i].color = models[i].diffuseColor; gpuModel->models[i].destructMesh = true; if(*models[i].diffuseTexturePath) { gpuModel->models[i].texture = assets->GetAsset<Gpu::Texture>(subDir, models[i].diffuseTexturePath); } if(*models[i].normalTexturePath) { gpuModel->models[i].normalMap = assets->GetAsset<Gpu::Texture>(subDir, models[i].normalTexturePath); } if(*models[i].cubeTexturePath) { gpuModel->models[i].cubeMap = assets->GetAsset<Gpu::CubeMap>(subDir, models[i].cubeTexturePath); } } asset = gpuModel; texTicket = -1; } return true; } return false; } unsigned ModelEncoder::GetEncodedBytes(LocalMesh * mesh) { if(!mesh) return sizeof(MeshMeta); unsigned verticesByteLength = mesh->vertexBuffer->GetLength() * mesh->vertexBuffer->GetElementSize(); unsigned indicesByteLength = mesh->GetNumIndices() * sizeof(unsigned); return sizeof(MeshMeta) + verticesByteLength + indicesByteLength; } char * ModelEncoder::EncodeMesh(LocalMesh * mesh, unsigned & outLength) { MeshMeta meshMeta(mesh); unsigned verticesByteLength = mesh->vertexBuffer->GetLength() * mesh->vertexBuffer->GetElementSize(); unsigned indicesByteLength = mesh->GetNumIndices() * sizeof(unsigned); outLength = sizeof(meshMeta) + verticesByteLength + indicesByteLength; char * data = new char[outLength]; memcpy(data, &meshMeta, sizeof(meshMeta)); memcpy(data + sizeof(meshMeta), mesh->vertexBuffer->GetData(), verticesByteLength); memcpy(data + sizeof(meshMeta) + verticesByteLength, mesh->indexBuffer, indicesByteLength); return data; } LocalMesh * ModelEncoder::DecodeMesh(char * data, unsigned dataLength) { if(!data || dataLength < sizeof(MeshMeta)) return 0; MeshMeta meshMeta; memcpy(&meshMeta, data, sizeof(meshMeta)); unsigned verticesByteLength = meshMeta.numVertices * VertApi::GetVertexSize(meshMeta.vertexType); unsigned indicesByteLength = meshMeta.numIndices * sizeof(unsigned); if(dataLength < sizeof(MeshMeta) + verticesByteLength + indicesByteLength) return 0; IVertexBuffer * vertexBuffer = 0; switch(meshMeta.vertexType) { case VertexType_Pos: vertexBuffer = new VertexBuffer<Vertex_Pos>(meshMeta.numVertices); break; case VertexType_PosCol: vertexBuffer = new VertexBuffer<Vertex_PosCol>(meshMeta.numVertices); break; case VertexType_PosNor: vertexBuffer = new VertexBuffer<Vertex_PosNor>(meshMeta.numVertices); break; case VertexType_PosTex: vertexBuffer = new VertexBuffer<Vertex_PosTex>(meshMeta.numVertices); break; case VertexType_PosNorTex: vertexBuffer = new VertexBuffer<Vertex_PosNorTex>(meshMeta.numVertices); break; case VertexType_PosNorTanTex: vertexBuffer = new VertexBuffer<Vertex_PosNorTanTex>(meshMeta.numVertices); break; } memcpy(vertexBuffer->GetData(), data + sizeof(MeshMeta), verticesByteLength); unsigned * indexBuffer = new unsigned[meshMeta.numIndices]; memcpy(indexBuffer, data + sizeof(MeshMeta) + verticesByteLength, indicesByteLength); return new LocalMesh(vertexBuffer, indexBuffer, meshMeta.numIndices); } char * ModelEncoder::EncodeModel(ModelMeta meta, unsigned & outLength) { unsigned meshLength = 0; char * meshData = EncodeMesh(meta.mesh, meshLength); meta.mesh = 0; outLength = sizeof(ModelMeta) + meshLength; char * data = new char[outLength]; memcpy(data, &meta, sizeof(ModelMeta)); memcpy(data + sizeof(ModelMeta), meshData, meshLength); delete[meshLength] meshData; return data; } ModelEncoder::ModelMeta ModelEncoder::DecodeModel(char * data, unsigned dataLength) { ModelMeta modelMeta; memcpy(&modelMeta, data, sizeof(ModelMeta)); modelMeta.mesh = DecodeMesh(data + sizeof(ModelMeta), dataLength - sizeof(ModelMeta)); return modelMeta; } char * ModelEncoder::EncodeModels(std::vector<ModelMeta> & models, unsigned & outLength) { outLength = 0; std::vector<char*> encodedModels; std::vector<unsigned> modelByteLengths; for(unsigned i = 0; i < models.size(); ++i) { modelByteLengths.push_back(0); encodedModels.push_back(EncodeModel(models[i], modelByteLengths[i])); outLength += modelByteLengths[i]; } unsigned currentByte = 0; char * data = new char[outLength]; for(unsigned i = 0; i < encodedModels.size(); ++i) { memcpy(data + currentByte, encodedModels[i], modelByteLengths[i]); delete[modelByteLengths[i]] encodedModels[i]; currentByte += modelByteLengths[i]; } return data; } std::vector<ModelEncoder::ModelMeta> ModelEncoder::DecodeModels(char * data, unsigned dataLength) { std::vector<ModelMeta> modelMetas; unsigned prevDataLength = dataLength; while(dataLength > sizeof(ModelMeta) && dataLength <= prevDataLength) { ModelMeta modelMeta = DecodeModel(data, dataLength); if(modelMeta.mesh) modelMetas.push_back(modelMeta); unsigned bytes = (sizeof(ModelMeta) + GetEncodedBytes(modelMetas.back().mesh)); prevDataLength = dataLength; dataLength -= bytes; data += bytes; } return modelMetas; } //Gpu::ComplexModel * ToGpuModel(Gpu::Api * gpu, std::vector<ModelEncoder::ModelMeta> & models) //{ // Gpu::ComplexModel * gpuModel = new Gpu::ComplexModel(models.size()); // // for(unsigned i = 0; i < models.size(); ++i) // { // gpuModel->models[i].mesh = models[i].mesh->ToGpuMesh(gpu); // gpuModel->models[i].color = models[i].diffuseColor; // //gpuModel->models[i]. // } //} } // namespace Ingenuity
; char *_memupr_(void *p, size_t n) SECTION code_string PUBLIC _memupr__callee EXTERN asm__memupr _memupr__callee: pop hl pop bc ex (sp),hl jp asm__memupr
; A099841: Expansion of (1-16*x)/(1-20*x+80*x^2). ; Submitted by Christian Krause ; 1,4,0,-320,-6400,-102400,-1536000,-22528000,-327680000,-4751360000,-68812800000,-996147200000,-14417920000000,-208666624000000,-3019898880000000,-43704647680000000,-632501043200000000,-9153649049600000000,-132472897536000000000 add $0,1 mov $3,4 lpb $0 sub $0,1 mov $2,$3 sub $2,$1 mul $1,2 mul $2,2 mul $3,6 add $3,$1 mul $1,8 add $1,$2 lpe mul $2,2 div $2,16 mov $0,$2
; A288834: a(n) = (n+1) * 3^(n-1). ; 2,9,36,135,486,1701,5832,19683,65610,216513,708588,2302911,7440174,23914845,76527504,243931419,774840978,2453663097,7748409780,24407490807,76709256822,240588123669,753145430616,2353579470675,7343167948506,22876792454961 mov $1,3 pow $1,$0 add $0,2 mul $1,$0 mov $0,$1
/* * Copyright (C) Volition, Inc. 1999. All rights reserved. * * All source code herein is the property of Volition, Inc. You may not sell * or otherwise commercially exploit the source or things you created based on * the source. */ /* * $Logfile: /Freespace2/code/Graphics/TmapScanTiled32x32.cpp $ * $Revision: 110 $ * $Date: 2002-06-09 06:41:30 +0200 (Sun, 09 Jun 2002) $ * $Author: relnev $ * * Routines for drawing tiled 32x32 textues * * $Log$ * Revision 1.3 2002/06/09 04:41:18 relnev * added copyright header * * Revision 1.2 2002/05/07 03:16:45 theoddone33 * The Great Newline Fix * * Revision 1.1.1.1 2002/05/03 03:28:09 root * Initial import. * * * 4 11/30/98 5:31p Dave * Fixed up Fred support for software mode. * * 3 11/30/98 1:07p Dave * 16 bit conversion, first run. * * 2 10/07/98 10:53a Dave * Initial checkin. * * 1 10/07/98 10:49a Dave * * 6 4/23/98 9:55a John * Fixed some bugs in the tiled tmapper causing bright dots to appear all * over models. * * 5 3/10/98 4:19p John * Cleaned up graphics lib. Took out most unused gr functions. Made D3D * & Glide have popups and print screen. Took out all >8bpp software * support. Made Fred zbuffer. Made zbuffer allocate dynamically to * support Fred. Made zbuffering key off of functions rather than one * global variable. * * 4 1/23/98 5:08p John * Took L out of vertex structure used B (blue) instead. Took all small * fireballs out of fireball types and used particles instead. Fixed some * debris explosion things. Restructured fireball code. Restructured * some lighting code. Made dynamic lighting on by default. Made groups * of lasers only cast one light. Made fireballs not cast light. * * 3 12/04/97 10:38a John * Fixed tiled texture mappers that were swapping uvs. * * 2 10/14/97 9:19a John * removed fdiv warnings. * * 1 6/18/97 4:02p John * added new code for 16x16 and 32x32 tiled tmaps. * * $NoKeywords: $ */ #include "3d.h" #include "2d.h" #include "grinternal.h" #include "tmapper.h" #include "tmapscanline.h" #include "floating.h" #include "palman.h" #include "fix.h" // Needed to keep warning 4725 to stay away. See PsTypes.h for details why. void disable_warning_4725_stub_tst32() { } void tmapscan_pln8_zbuffered_tiled_32x32() { Tmap.fx_l = fl2f(Tmap.l.b*32.0); Tmap.fx_l_right = fl2f(Tmap.r.b*32.0); Tmap.fx_dl_dx = fl2f(Tmap.deltas.b*32.0); if ( Tmap.fx_dl_dx < 0 ) { Tmap.fx_dl_dx = -Tmap.fx_dl_dx; Tmap.fx_l = (67*F1_0)-Tmap.fx_l; Tmap.fx_l_right = (67*F1_0)-Tmap.fx_l_right; // Assert( Tmap.fx_l > 31*F1_0 ); // Assert( Tmap.fx_l < 66*F1_0 ); // Assert( Tmap.fx_dl_dx >= 0 ); // Assert( Tmap.fx_dl_dx < 31*F1_0 ); } Tmap.fl_dudx_wide = Tmap.deltas.u*32.0f; Tmap.fl_dvdx_wide = Tmap.deltas.v*32.0f; Tmap.fl_dwdx_wide = Tmap.deltas.sw*32.0f; Tmap.fx_w = fl2i(Tmap.l.sw * GR_Z_RANGE)+gr_zoffset; Tmap.fx_dwdx = fl2i(Tmap.deltas.sw * GR_Z_RANGE); // Assert(Tmap.fx_w < 65536 ); // Assert(Tmap.fx_w >= 0 ); // Assert(Tmap.fx_w+Tmap.fx_dwdx*Tmap.loop_count < 65536 ); // Assert(Tmap.fx_w+Tmap.fx_dwdx*Tmap.loop_count >= 0 ); #ifdef PLAT_UNIX STUB_FUNCTION; #else _asm { push eax push ecx push edx push ebx push ebp push esi push edi // Put the FPU in low precision mode fstcw Tmap.OldFPUCW // store copy of CW mov ax,Tmap.OldFPUCW // get it in ax and eax, ~0x300L mov Tmap.FPUCW,ax // store it fldcw Tmap.FPUCW // load the FPU mov ecx, Tmap.loop_count // ecx = width mov edi, Tmap.dest_row_data // edi = dest pointer // edi = pointer to start pixel in dest dib // ecx = spanwidth mov eax,ecx // eax and ecx = width shr ecx,5 // ecx = width / subdivision length and eax,31 // eax = width mod subdivision length jnz some_left_over // any leftover? dec ecx // no, so special case last span mov eax,32 // it's 8 pixels long some_left_over: mov Tmap.Subdivisions,ecx // store widths mov Tmap.WidthModLength,eax // calculate ULeft and VLeft // FPU Stack (ZL = ZLeft) // st0 st1 st2 st3 st4 st5 st6 st7 fld Tmap.l.v // V/ZL fld Tmap.l.u // U/ZL V/ZL fld Tmap.l.sw // 1/ZL U/ZL V/ZL fld1 // 1 1/ZL U/ZL V/ZL fdiv st,st(1) // ZL 1/ZL U/ZL V/ZL fld st // ZL ZL 1/ZL U/ZL V/ZL fmul st,st(4) // VL ZL 1/ZL U/ZL V/ZL fxch st(1) // ZL VL 1/ZL U/ZL V/ZL fmul st,st(3) // UL VL 1/ZL U/ZL V/ZL fstp st(5) // VL 1/ZL U/ZL V/ZL UL fstp st(5) // 1/ZL U/ZL V/ZL UL VL // calculate right side OverZ terms ; st0 st1 st2 st3 st4 st5 st6 st7 fadd Tmap.fl_dwdx_wide // 1/ZR U/ZL V/ZL UL VL fxch st(1) // U/ZL 1/ZR V/ZL UL VL fadd Tmap.fl_dudx_wide // U/ZR 1/ZR V/ZL UL VL fxch st(2) // V/ZL 1/ZR U/ZR UL VL fadd Tmap.fl_dvdx_wide // V/ZR 1/ZR U/ZR UL VL // calculate right side coords // st0 st1 st2 st3 st4 st5 st6 st7 fld1 // 1 V/ZR 1/ZR U/ZR UL VL // @todo overlap this guy fdiv st,st(2) // ZR V/ZR 1/ZR U/ZR UL VL fld st // ZR ZR V/ZR 1/ZR U/ZR UL VL fmul st,st(2) // VR ZR V/ZR 1/ZR U/ZR UL VL fxch st(1) // ZR VR V/ZR 1/ZR U/ZR UL VL fmul st,st(4) // UR VR V/ZR 1/ZR U/ZR UL VL cmp ecx,0 // check for any full spans jle HandleLeftoverPixels SpanLoop: // at this point the FPU contains // st0 st1 st2 st3 st4 st5 st6 st7 // UR VR V/ZR 1/ZR U/ZR UL VL // convert left side coords fld st(5) ; UL UR VR V/ZR 1/ZR U/ZR UL VL fmul Tmap.FixedScale ; UL16 UR VR V/ZR 1/ZR U/ZR UL VL fistp Tmap.UFixed ; UR VR V/ZR 1/ZR U/ZR UL VL fld st(6) ; VL UR VR V/ZR 1/ZR U/ZR UL VL fmul Tmap.FixedScale ; VL16 UR VR V/ZR 1/ZR U/ZR UL VL fistp Tmap.VFixed ; UR VR V/ZR 1/ZR U/ZR UL VL // calculate deltas ; st0 st1 st2 st3 st4 st5 st6 st7 fsubr st(5),st ; UR VR V/ZR 1/ZR U/ZR dU VL fxch st(1) ; VR UR V/ZR 1/ZR U/ZR dU VL fsubr st(6),st ; VR UR V/ZR 1/ZR U/ZR dU dV fxch st(6) ; dV UR V/ZR 1/ZR U/ZR dU VR fmul Tmap.FixedScale8 ; dV8 UR V/ZR 1/ZR U/ZR dU VR fistp Tmap.DeltaV ; UR V/ZR 1/ZR U/ZR dU VR fxch st(4) ; dU V/ZR 1/ZR U/ZR UR VR fmul Tmap.FixedScale8 ; dU8 V/ZR 1/ZR U/ZR UR VR fistp Tmap.DeltaU ; V/ZR 1/ZR U/ZR UR VR // increment terms for next span // st0 st1 st2 st3 st4 st5 st6 st7 // Right terms become Left terms--->// V/ZL 1/ZL U/ZL UL VL fadd Tmap.fl_dvdx_wide // V/ZR 1/ZL U/ZL UL VL fxch st(1) // 1/ZL V/ZR U/ZL UL VL fadd Tmap.fl_dwdx_wide // 1/ZR V/ZR U/ZL UL VL fxch st(2) // U/ZL V/ZR 1/ZR UL VL fadd Tmap.fl_dudx_wide // U/ZR V/ZR 1/ZR UL VL fxch st(2) // 1/ZR V/ZR U/ZR UL VL fxch st(1) // V/ZR 1/ZR U/ZR UL VL // setup delta values mov eax,Tmap.DeltaV // get v 16.16 step mov ebx,eax // copy it sar eax,16 // get v int step shl ebx,16 // get v frac step mov Tmap.DeltaVFrac,ebx // store it imul eax,Tmap.src_offset // calculate texture step for v int step mov ebx,Tmap.DeltaU // get u 16.16 step mov ecx,ebx // copy it sar ebx,16 // get u int step shl ecx,16 // get u frac step mov Tmap.DeltaUFrac,ecx // store it add eax,ebx // calculate uint + vint step mov Tmap.uv_delta[4],eax // save whole step in non-v-carry slot add eax,Tmap.src_offset // calculate whole step + v carry mov Tmap.uv_delta[0],eax // save in v-carry slot // setup initial coordinates mov esi,Tmap.UFixed // get u 16.16 fixedpoint coordinate mov ebx,esi // copy it sar esi,16 // get integer part shl ebx,16 // get fractional part mov ecx,Tmap.VFixed // get v 16.16 fixedpoint coordinate mov edx,ecx // copy it sar edx,16 // get integer part shl ecx,16 // get fractional part imul edx,Tmap.src_offset // calc texture scanline address add esi,edx // calc texture offset add esi,Tmap.pixptr // calc address // set up affine registers mov eax, Tmap.fx_l shr eax, 8 mov bx, ax mov ebp, Tmap.fx_dl_dx shl ebp, 5 //*32 add Tmap.fx_l, ebp mov ebp, Tmap.fx_l shr ebp, 8 sub bp, ax shr bp, 5 mov dx, bp // calculate right side coords st0 st1 st2 st3 st4 st5 st6 st7 fld1 // 1 V/ZR 1/ZR U/ZR UL VL // This divide should happen while the pixel span is drawn. fdiv st,st(2) // ZR V/ZR 1/ZR U/ZR UL VL // 8 pixel span code // edi = dest dib bits at current pixel // esi = texture pointer at current u,v // eax = scratch // ebx = u fraction 0.32 // ecx = v fraction 0.32 // edx = u frac step // ebp = v carry scratch mov al,[edi] // preread the destination cache line mov Tmap.InnerLooper, 32/4 // Set up loop counter mov eax, edi sub eax, Tmap.pScreenBits mov edx, gr_zbuffer shl eax, 2 add edx, eax // Make ESI = DV:DU in 5:11,5:11 format mov eax, Tmap.DeltaV shr eax, 5 mov esi, Tmap.DeltaU shl esi, 11 mov si, ax mov Tmap.DeltaUFrac, esi // Make ECX = V:U in 5:11,5:11 format mov eax, Tmap.VFixed shr eax, 5 mov ecx, Tmap.UFixed shl ecx, 11 mov cx, ax mov esi, Tmap.fx_w // eax = tmp // ebx = light // ecx = V:U in 8.6:10.8 // edx = zbuffer pointer // esi = z // edi = screen data // ebp = dl_dx InnerInnerLoop: // pixel 0 cmp esi, [edx+0] // Compare the Z depth of this pixel with zbuffer jle Skip0 // If pixel is covered, skip drawing mov [edx+0], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al Skip0: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp // pixel 1 cmp esi, [edx+4] // Compare the Z depth of this pixel with zbuffer jle Skip1 // If pixel is covered, skip drawing mov [edx+4], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+1], al Skip1: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp // pixel 2 cmp esi, [edx+8] // Compare the Z depth of this pixel with zbuffer jle Skip2 // If pixel is covered, skip drawing mov [edx+8], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+2], al Skip2: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp // pixel 3 cmp esi, [edx+12] // Compare the Z depth of this pixel with zbuffer jle Skip3 // If pixel is covered, skip drawing mov [edx+12], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+3], al Skip3: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp add edi, 4 add edx, 16 dec Tmap.InnerLooper jnz InnerInnerLoop mov Tmap.fx_w, esi // the fdiv is done, finish right // st0 st1 st2 st3 st4 st5 st6 st7 // ZR V/ZR 1/ZR U/ZR UL VL fld st // ZR ZR V/ZR 1/ZR U/ZR UL VL fmul st,st(2) // VR ZR V/ZR 1/ZR U/ZR UL VL fxch st(1) // ZR VR V/ZR 1/ZR U/ZR UL VL fmul st,st(4) // UR VR V/ZR 1/ZR U/ZR UL VL dec Tmap.Subdivisions // decrement span count jnz SpanLoop // loop back HandleLeftoverPixels: mov esi,Tmap.pixptr // load texture pointer // edi = dest dib bits // esi = current texture dib bits // at this point the FPU contains ; st0 st1 st2 st3 st4 st5 st6 st7 // inv. means invalid numbers ; inv. inv. inv. inv. inv. UL VL cmp Tmap.WidthModLength,0 ; are there remaining pixels to draw? jz FPUReturn ; nope, pop the FPU and bail // convert left side coords ; st0 st1 st2 st3 st4 st5 st6 st7 fld st(5) ; UL inv. inv. inv. inv. inv. UL VL fmul Tmap.FixedScale ; UL16 inv. inv. inv. inv. inv. UL VL fistp Tmap.UFixed ; inv. inv. inv. inv. inv. UL VL fld st(6) ; VL inv. inv. inv. inv. inv. UL VL fmul Tmap.FixedScale // VL16 inv. inv. inv. inv. inv. UL VL fistp Tmap.VFixed ; inv. inv. inv. inv. inv. UL VL dec Tmap.WidthModLength ; calc how many steps to take jz OnePixelSpan ; just one, don't do deltas' // calculate right edge coordinates ; st0 st1 st2 st3 st4 st5 st6 st7 // r -> R+1 // @todo rearrange things so we don't need these two instructions fstp Tmap.FloatTemp ; inv. inv. inv. inv. UL VL fstp Tmap.FloatTemp ; inv. inv. inv. UL VL fld Tmap.r.v ; V/Zr inv. inv. inv. UL VL fsub Tmap.deltas.v ; V/ZR inv. inv. inv. UL VL fld Tmap.r.u ; U/Zr V/ZR inv. inv. inv. UL VL fsub Tmap.deltas.u ; U/ZR V/ZR inv. inv. inv. UL VL fld Tmap.r.sw ; 1/Zr U/ZR V/ZR inv. inv. inv. UL VL fsub Tmap.deltas.sw ; 1/ZR U/ZR V/ZR inv. inv. inv. UL VL fdivr Tmap.One ; ZR U/ZR V/ZR inv. inv. inv. UL VL fmul st(1),st ; ZR UR V/ZR inv. inv. inv. UL VL fmulp st(2),st ; UR VR inv. inv. inv. UL VL // calculate deltas ; st0 st1 st2 st3 st4 st5 st6 st7 fsubr st(5),st ; UR VR inv. inv. inv. dU VL fxch st(1) ; VR UR inv. inv. inv. dU VL fsubr st(6),st ; VR UR inv. inv. inv. dU dV fxch st(6) ; dV UR inv. inv. inv. dU VR fidiv Tmap.WidthModLength ; dv UR inv. inv. inv. dU VR fmul Tmap.FixedScale ; dv16 UR inv. inv. inv. dU VR fistp Tmap.DeltaV ; UR inv. inv. inv. dU VR fxch st(4) ; dU inv. inv. inv. UR VR fidiv Tmap.WidthModLength ; du inv. inv. inv. UR VR fmul Tmap.FixedScale ; du16 inv. inv. inv. UR VR fistp Tmap.DeltaU ; inv. inv. inv. UR VR // @todo gross! these are to line up with the other loop fld st(1) ; inv. inv. inv. inv. UR VR fld st(2) ; inv. inv. inv. inv. inv. UR VR // setup delta values mov eax, Tmap.DeltaV // get v 16.16 step mov ebx, eax // copy it sar eax, 16 // get v int step shl ebx, 16 // get v frac step mov Tmap.DeltaVFrac, ebx // store it imul eax, Tmap.src_offset // calc texture step for v int step mov ebx, Tmap.DeltaU // get u 16.16 step mov ecx, ebx // copy it sar ebx, 16 // get the u int step shl ecx, 16 // get the u frac step mov Tmap.DeltaUFrac, ecx // store it add eax, ebx // calc uint + vint step mov Tmap.uv_delta[4], eax // save whole step in non-v-carry slot add eax, Tmap.src_offset // calc whole step + v carry mov Tmap.uv_delta[0], eax // save in v-carry slot OnePixelSpan: ; setup initial coordinates mov esi, Tmap.UFixed // get u 16.16 mov ebx, esi // copy it sar esi, 16 // get integer part shl ebx, 16 // get fractional part mov ecx, Tmap.VFixed // get v 16.16 mov edx, ecx // copy it sar edx, 16 // get integer part shl ecx, 16 // get fractional part imul edx, Tmap.src_offset // calc texture scanline address add esi, edx // calc texture offset add esi, Tmap.pixptr // calc address mov eax, Tmap.fx_l shr eax, 8 mov bx, ax // mov edx, Tmap.DeltaUFrac push ebx mov ebx, Tmap.fx_l_right shr ebx, 8 sub ebx, eax mov eax, ebx mov eax, Tmap.fx_dl_dx shr eax, 8 mov bp, ax pop ebx mov eax, edi sub eax, Tmap.pScreenBits mov edx, gr_zbuffer shl eax, 2 add edx, eax inc Tmap.WidthModLength mov eax,Tmap.WidthModLength shr eax, 1 jz one_more_pix pushf mov Tmap.WidthModLength, eax xor eax, eax mov al,[edi] // preread the destination cache line // Make ESI = DV:DU in 6:10,6:10 format mov eax, Tmap.DeltaV shr eax, 5 mov esi, Tmap.DeltaU shl esi, 11 mov si, ax mov Tmap.DeltaUFrac, esi // Make ECX = V:U in 6:10,6:10 format mov eax, Tmap.VFixed shr eax, 5 mov ecx, Tmap.UFixed shl ecx, 11 mov cx, ax mov esi, Tmap.fx_w // eax = tmp // ebx = light // ecx = V:U in 8.6:10.8 // edx = zbuffer pointer // esi = z // edi = screen data // ebp = dl_dx NextPixel: // pixel 0 cmp esi, [edx+0] // Compare the Z depth of this pixel with zbuffer jle Skip0a // If pixel is covered, skip drawing mov [edx+0], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al Skip0a: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp // pixel 1 cmp esi, [edx+4] // Compare the Z depth of this pixel with zbuffer jle Skip1a // If pixel is covered, skip drawing mov [edx+4], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+1], al Skip1a: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp add edi, 2 add edx, 8 dec Tmap.WidthModLength jg NextPixel popf jnc FPUReturn one_more_pix: // pixel 0 cmp esi, [edx+0] // Compare the Z depth of this pixel with zbuffer jle Skip0b // If pixel is covered, skip drawing mov [edx+0], esi // Write z mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al Skip0b: add ecx, Tmap.DeltaUFrac add esi, Tmap.fx_dwdx add ebx, ebp FPUReturn: // busy FPU registers: // st0 st1 st2 st3 st4 st5 st6 st7 // xxx xxx xxx xxx xxx xxx xxx ffree st(0) ffree st(1) ffree st(2) ffree st(3) ffree st(4) ffree st(5) ffree st(6) fldcw Tmap.OldFPUCW // restore the FPU pop edi pop esi pop ebp pop ebx pop edx pop ecx pop eax } #endif } void tmapscan_pln8_tiled_32x32() { if (gr_zbuffering) { switch(gr_zbuffering_mode) { case GR_ZBUFF_NONE: break; case GR_ZBUFF_FULL: // both tmapscan_pln8_zbuffered_tiled_32x32(); return; case GR_ZBUFF_WRITE: // write only tmapscan_pln8_zbuffered_tiled_32x32(); break; case GR_ZBUFF_READ: // read only tmapscan_pln8_zbuffered_tiled_32x32(); return; } } Tmap.fx_l = fl2f(Tmap.l.b*32.0); Tmap.fx_l_right = fl2f(Tmap.r.b*32.0); Tmap.fx_dl_dx = fl2f(Tmap.deltas.b*32.0); if ( Tmap.fx_dl_dx < 0 ) { Tmap.fx_dl_dx = -Tmap.fx_dl_dx; Tmap.fx_l = (67*F1_0)-Tmap.fx_l; Tmap.fx_l_right = (67*F1_0)-Tmap.fx_l_right; // Assert( Tmap.fx_l > 31*F1_0 ); // Assert( Tmap.fx_l < 66*F1_0 ); // Assert( Tmap.fx_dl_dx >= 0 ); // Assert( Tmap.fx_dl_dx < 31*F1_0 ); } Tmap.fl_dudx_wide = Tmap.deltas.u*32.0f; Tmap.fl_dvdx_wide = Tmap.deltas.v*32.0f; Tmap.fl_dwdx_wide = Tmap.deltas.sw*32.0f; Tmap.fx_w = fl2i(Tmap.l.sw * GR_Z_RANGE)+gr_zoffset; Tmap.fx_dwdx = fl2i(Tmap.deltas.sw * GR_Z_RANGE); // Assert(Tmap.fx_w < 65536 ); // Assert(Tmap.fx_w >= 0 ); // Assert(Tmap.fx_w+Tmap.fx_dwdx*Tmap.loop_count < 65536 ); // Assert(Tmap.fx_w+Tmap.fx_dwdx*Tmap.loop_count >= 0 ); #ifdef PLAT_UNIX STUB_FUNCTION; #else _asm { push eax push ecx push edx push ebx push ebp push esi push edi // Put the FPU in low precision mode fstcw Tmap.OldFPUCW // store copy of CW mov ax,Tmap.OldFPUCW // get it in ax and eax, ~0x300L mov Tmap.FPUCW,ax // store it fldcw Tmap.FPUCW // load the FPU mov ecx, Tmap.loop_count // ecx = width mov edi, Tmap.dest_row_data // edi = dest pointer // edi = pointer to start pixel in dest dib // ecx = spanwidth mov eax,ecx // eax and ecx = width shr ecx,5 // ecx = width / subdivision length and eax,31 // eax = width mod subdivision length jnz some_left_over // any leftover? dec ecx // no, so special case last span mov eax,32 // it's 8 pixels long some_left_over: mov Tmap.Subdivisions,ecx // store widths mov Tmap.WidthModLength,eax // calculate ULeft and VLeft // FPU Stack (ZL = ZLeft) // st0 st1 st2 st3 st4 st5 st6 st7 fld Tmap.l.v // V/ZL fld Tmap.l.u // U/ZL V/ZL fld Tmap.l.sw // 1/ZL U/ZL V/ZL fld1 // 1 1/ZL U/ZL V/ZL fdiv st,st(1) // ZL 1/ZL U/ZL V/ZL fld st // ZL ZL 1/ZL U/ZL V/ZL fmul st,st(4) // VL ZL 1/ZL U/ZL V/ZL fxch st(1) // ZL VL 1/ZL U/ZL V/ZL fmul st,st(3) // UL VL 1/ZL U/ZL V/ZL fstp st(5) // VL 1/ZL U/ZL V/ZL UL fstp st(5) // 1/ZL U/ZL V/ZL UL VL // calculate right side OverZ terms ; st0 st1 st2 st3 st4 st5 st6 st7 fadd Tmap.fl_dwdx_wide // 1/ZR U/ZL V/ZL UL VL fxch st(1) // U/ZL 1/ZR V/ZL UL VL fadd Tmap.fl_dudx_wide // U/ZR 1/ZR V/ZL UL VL fxch st(2) // V/ZL 1/ZR U/ZR UL VL fadd Tmap.fl_dvdx_wide // V/ZR 1/ZR U/ZR UL VL // calculate right side coords // st0 st1 st2 st3 st4 st5 st6 st7 fld1 // 1 V/ZR 1/ZR U/ZR UL VL // @todo overlap this guy fdiv st,st(2) // ZR V/ZR 1/ZR U/ZR UL VL fld st // ZR ZR V/ZR 1/ZR U/ZR UL VL fmul st,st(2) // VR ZR V/ZR 1/ZR U/ZR UL VL fxch st(1) // ZR VR V/ZR 1/ZR U/ZR UL VL fmul st,st(4) // UR VR V/ZR 1/ZR U/ZR UL VL cmp ecx,0 // check for any full spans jle HandleLeftoverPixels SpanLoop: // at this point the FPU contains // st0 st1 st2 st3 st4 st5 st6 st7 // UR VR V/ZR 1/ZR U/ZR UL VL // convert left side coords fld st(5) ; UL UR VR V/ZR 1/ZR U/ZR UL VL fmul Tmap.FixedScale ; UL16 UR VR V/ZR 1/ZR U/ZR UL VL fistp Tmap.UFixed ; UR VR V/ZR 1/ZR U/ZR UL VL fld st(6) ; VL UR VR V/ZR 1/ZR U/ZR UL VL fmul Tmap.FixedScale ; VL16 UR VR V/ZR 1/ZR U/ZR UL VL fistp Tmap.VFixed ; UR VR V/ZR 1/ZR U/ZR UL VL // calculate deltas ; st0 st1 st2 st3 st4 st5 st6 st7 fsubr st(5),st ; UR VR V/ZR 1/ZR U/ZR dU VL fxch st(1) ; VR UR V/ZR 1/ZR U/ZR dU VL fsubr st(6),st ; VR UR V/ZR 1/ZR U/ZR dU dV fxch st(6) ; dV UR V/ZR 1/ZR U/ZR dU VR fmul Tmap.FixedScale8 ; dV8 UR V/ZR 1/ZR U/ZR dU VR fistp Tmap.DeltaV ; UR V/ZR 1/ZR U/ZR dU VR fxch st(4) ; dU V/ZR 1/ZR U/ZR UR VR fmul Tmap.FixedScale8 ; dU8 V/ZR 1/ZR U/ZR UR VR fistp Tmap.DeltaU ; V/ZR 1/ZR U/ZR UR VR // increment terms for next span // st0 st1 st2 st3 st4 st5 st6 st7 // Right terms become Left terms--->// V/ZL 1/ZL U/ZL UL VL fadd Tmap.fl_dvdx_wide // V/ZR 1/ZL U/ZL UL VL fxch st(1) // 1/ZL V/ZR U/ZL UL VL fadd Tmap.fl_dwdx_wide // 1/ZR V/ZR U/ZL UL VL fxch st(2) // U/ZL V/ZR 1/ZR UL VL fadd Tmap.fl_dudx_wide // U/ZR V/ZR 1/ZR UL VL fxch st(2) // 1/ZR V/ZR U/ZR UL VL fxch st(1) // V/ZR 1/ZR U/ZR UL VL // setup delta values mov eax,Tmap.DeltaV // get v 16.16 step mov ebx,eax // copy it sar eax,16 // get v int step shl ebx,16 // get v frac step mov Tmap.DeltaVFrac,ebx // store it imul eax,Tmap.src_offset // calculate texture step for v int step mov ebx,Tmap.DeltaU // get u 16.16 step mov ecx,ebx // copy it sar ebx,16 // get u int step shl ecx,16 // get u frac step mov Tmap.DeltaUFrac,ecx // store it add eax,ebx // calculate uint + vint step mov Tmap.uv_delta[4],eax // save whole step in non-v-carry slot add eax,Tmap.src_offset // calculate whole step + v carry mov Tmap.uv_delta[0],eax // save in v-carry slot // setup initial coordinates mov esi,Tmap.UFixed // get u 16.16 fixedpoint coordinate mov ebx,esi // copy it sar esi,16 // get integer part shl ebx,16 // get fractional part mov ecx,Tmap.VFixed // get v 16.16 fixedpoint coordinate mov edx,ecx // copy it sar edx,16 // get integer part shl ecx,16 // get fractional part imul edx,Tmap.src_offset // calc texture scanline address add esi,edx // calc texture offset add esi,Tmap.pixptr // calc address // set up affine registers mov eax, Tmap.fx_l shr eax, 8 mov bx, ax mov ebp, Tmap.fx_dl_dx shl ebp, 5 //*32 add Tmap.fx_l, ebp mov ebp, Tmap.fx_l shr ebp, 8 sub bp, ax shr bp, 5 mov dx, bp // calculate right side coords st0 st1 st2 st3 st4 st5 st6 st7 fld1 // 1 V/ZR 1/ZR U/ZR UL VL // This divide should happen while the pixel span is drawn. fdiv st,st(2) // ZR V/ZR 1/ZR U/ZR UL VL // 8 pixel span code // edi = dest dib bits at current pixel // esi = texture pointer at current u,v // eax = scratch // ebx = u fraction 0.32 // ecx = v fraction 0.32 // edx = u frac step // ebp = v carry scratch mov al,[edi] // preread the destination cache line mov Tmap.InnerLooper, 32/4 // Set up loop counter mov eax, edi sub eax, Tmap.pScreenBits mov edx, gr_zbuffer shl eax, 2 add edx, eax // Make ESI = DV:DU in 6:10,6:10 format mov eax, Tmap.DeltaU shr eax, 5 mov esi, Tmap.DeltaV shl esi, 11 mov si, ax mov Tmap.DeltaUFrac, esi // Make ECX = V:U in 6:10,6:10 format mov eax, Tmap.UFixed shr eax, 5 mov ecx, Tmap.VFixed shl ecx, 11 mov cx, ax // eax = tmp // ebx = light // ecx = V:U in 8.6:10.8 // edx = zbuffer pointer // esi = z // edi = screen data // ebp = dl_dx InnerInnerLoop: // pixel 0 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al add ecx, Tmap.DeltaUFrac add ebx, ebp // pixel 1 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+1], al add ecx, Tmap.DeltaUFrac add ebx, ebp // pixel 2 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+2], al add ecx, Tmap.DeltaUFrac add ebx, ebp // pixel 3 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+3], al add ecx, Tmap.DeltaUFrac add ebx, ebp add edi, 4 dec Tmap.InnerLooper jnz InnerInnerLoop mov Tmap.fx_w, esi // the fdiv is done, finish right // st0 st1 st2 st3 st4 st5 st6 st7 // ZR V/ZR 1/ZR U/ZR UL VL fld st // ZR ZR V/ZR 1/ZR U/ZR UL VL fmul st,st(2) // VR ZR V/ZR 1/ZR U/ZR UL VL fxch st(1) // ZR VR V/ZR 1/ZR U/ZR UL VL fmul st,st(4) // UR VR V/ZR 1/ZR U/ZR UL VL dec Tmap.Subdivisions // decrement span count jnz SpanLoop // loop back HandleLeftoverPixels: mov esi,Tmap.pixptr // load texture pointer // edi = dest dib bits // esi = current texture dib bits // at this point the FPU contains ; st0 st1 st2 st3 st4 st5 st6 st7 // inv. means invalid numbers ; inv. inv. inv. inv. inv. UL VL cmp Tmap.WidthModLength,0 ; are there remaining pixels to draw? jz FPUReturn ; nope, pop the FPU and bail // convert left side coords ; st0 st1 st2 st3 st4 st5 st6 st7 fld st(5) ; UL inv. inv. inv. inv. inv. UL VL fmul Tmap.FixedScale ; UL16 inv. inv. inv. inv. inv. UL VL fistp Tmap.UFixed ; inv. inv. inv. inv. inv. UL VL fld st(6) ; VL inv. inv. inv. inv. inv. UL VL fmul Tmap.FixedScale // VL16 inv. inv. inv. inv. inv. UL VL fistp Tmap.VFixed ; inv. inv. inv. inv. inv. UL VL dec Tmap.WidthModLength ; calc how many steps to take jz OnePixelSpan ; just one, don't do deltas' // calculate right edge coordinates ; st0 st1 st2 st3 st4 st5 st6 st7 // r -> R+1 // @todo rearrange things so we don't need these two instructions fstp Tmap.FloatTemp ; inv. inv. inv. inv. UL VL fstp Tmap.FloatTemp ; inv. inv. inv. UL VL fld Tmap.r.v ; V/Zr inv. inv. inv. UL VL fsub Tmap.deltas.v ; V/ZR inv. inv. inv. UL VL fld Tmap.r.u ; U/Zr V/ZR inv. inv. inv. UL VL fsub Tmap.deltas.u ; U/ZR V/ZR inv. inv. inv. UL VL fld Tmap.r.sw ; 1/Zr U/ZR V/ZR inv. inv. inv. UL VL fsub Tmap.deltas.sw ; 1/ZR U/ZR V/ZR inv. inv. inv. UL VL fdivr Tmap.One ; ZR U/ZR V/ZR inv. inv. inv. UL VL fmul st(1),st ; ZR UR V/ZR inv. inv. inv. UL VL fmulp st(2),st ; UR VR inv. inv. inv. UL VL // calculate deltas ; st0 st1 st2 st3 st4 st5 st6 st7 fsubr st(5),st ; UR VR inv. inv. inv. dU VL fxch st(1) ; VR UR inv. inv. inv. dU VL fsubr st(6),st ; VR UR inv. inv. inv. dU dV fxch st(6) ; dV UR inv. inv. inv. dU VR fidiv Tmap.WidthModLength ; dv UR inv. inv. inv. dU VR fmul Tmap.FixedScale ; dv16 UR inv. inv. inv. dU VR fistp Tmap.DeltaV ; UR inv. inv. inv. dU VR fxch st(4) ; dU inv. inv. inv. UR VR fidiv Tmap.WidthModLength ; du inv. inv. inv. UR VR fmul Tmap.FixedScale ; du16 inv. inv. inv. UR VR fistp Tmap.DeltaU ; inv. inv. inv. UR VR // @todo gross! these are to line up with the other loop fld st(1) ; inv. inv. inv. inv. UR VR fld st(2) ; inv. inv. inv. inv. inv. UR VR // setup delta values mov eax, Tmap.DeltaV // get v 16.16 step mov ebx, eax // copy it sar eax, 16 // get v int step shl ebx, 16 // get v frac step mov Tmap.DeltaVFrac, ebx // store it imul eax, Tmap.src_offset // calc texture step for v int step mov ebx, Tmap.DeltaU // get u 16.16 step mov ecx, ebx // copy it sar ebx, 16 // get the u int step shl ecx, 16 // get the u frac step mov Tmap.DeltaUFrac, ecx // store it add eax, ebx // calc uint + vint step mov Tmap.uv_delta[4], eax // save whole step in non-v-carry slot add eax, Tmap.src_offset // calc whole step + v carry mov Tmap.uv_delta[0], eax // save in v-carry slot OnePixelSpan: ; setup initial coordinates mov esi, Tmap.UFixed // get u 16.16 mov ebx, esi // copy it sar esi, 16 // get integer part shl ebx, 16 // get fractional part mov ecx, Tmap.VFixed // get v 16.16 mov edx, ecx // copy it sar edx, 16 // get integer part shl ecx, 16 // get fractional part imul edx, Tmap.src_offset // calc texture scanline address add esi, edx // calc texture offset add esi, Tmap.pixptr // calc address mov eax, Tmap.fx_l shr eax, 8 mov bx, ax // mov edx, Tmap.DeltaUFrac push ebx mov ebx, Tmap.fx_l_right shr ebx, 8 sub ebx, eax mov eax, ebx mov eax, Tmap.fx_dl_dx shr eax, 8 mov bp, ax pop ebx mov eax, edi sub eax, Tmap.pScreenBits mov edx, gr_zbuffer shl eax, 2 add edx, eax inc Tmap.WidthModLength mov eax,Tmap.WidthModLength shr eax, 1 jz one_more_pix pushf mov Tmap.WidthModLength, eax xor eax, eax mov al,[edi] // preread the destination cache line // Make ESI = DV:DU in 6:10,6:10 format mov eax, Tmap.DeltaU shr eax, 5 mov esi, Tmap.DeltaV shl esi, 11 mov si, ax mov Tmap.DeltaUFrac, esi // Make ECX = V:U in 6:10,6:10 format mov eax, Tmap.UFixed shr eax, 5 mov ecx, Tmap.VFixed shl ecx, 11 mov cx, ax mov esi, Tmap.fx_w // eax = tmp // ebx = light // ecx = V:U in 8.6:10.8 // edx = zbuffer pointer // esi = z // edi = screen data // ebp = dl_dx NextPixel: // pixel 0 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al add ecx, Tmap.DeltaUFrac add ebx, ebp // pixel 1 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+1], al add ecx, Tmap.DeltaUFrac add ebx, ebp add edi, 2 add edx, 8 dec Tmap.WidthModLength jg NextPixel popf jnc FPUReturn one_more_pix: // pixel 0 mov eax, ecx // EAX = V.VF:U.UF in 6.10:6.10 shr ax, 11 // EAX = V:U in 6.10:16.0 rol eax, 5 // EAX = V:U in 0.0:6:6 and eax, 03ffh // clear upper bits add eax, Tmap.pixptr // EAX = (V*64)+U + Pixptr mov al, [eax] mov ah, bh and eax, 0ffffh // clear upper bits mov al, gr_fade_table[eax] mov [edi+0], al add ecx, Tmap.DeltaUFrac add ebx, ebp FPUReturn: // busy FPU registers: // st0 st1 st2 st3 st4 st5 st6 st7 // xxx xxx xxx xxx xxx xxx xxx ffree st(0) ffree st(1) ffree st(2) ffree st(3) ffree st(4) ffree st(5) ffree st(6) fldcw Tmap.OldFPUCW // restore the FPU pop edi pop esi pop ebp pop ebx pop edx pop ecx pop eax } #endif }
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Copyright (c) GeoWorks 1992 -- All Rights Reserved PROJECT: MODULE: FILE: blackholepref.asm AUTHOR: Adam de Boor, Dec 3, 1992 ROUTINES: Name Description ---- ----------- REVISION HISTORY: Name Date Description ---- ---- ----------- Adam 12/ 3/92 Initial revision DESCRIPTION: Saver-specific preferences for BlackHole saver. $Id: blackholepref.asm,v 1.1 97/04/04 16:44:19 newdeal Exp $ %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@ ; include the standard suspects include geos.def include geode.def include lmem.def include object.def include graphics.def include gstring.def UseLib ui.def include vmdef.def ; contains macros that allow us to create a ; VM file in this way. UseLib config.def ; Most objects we use come from here UseLib saver.def ; Might need some of the constants from ; here, though we can't use objects from here. ; ; Define the VMAttributes used for the file. ; ATTRIBUTES equ PREFVM_ATTRIBUTES ; ; Include constants from BlackHole, the saver, for use in our objects. ; include ../blackhole.def ; ; Now the object tree. ; include blackholepref.rdef ; ; Define the map block for the VM file, which Preferences will use to get ; to the root of the tree we hold. ; DefVMBlock MapBlock PrefVMMapBlock <RootObject> EndVMBlock MapBlock