text stringlengths 1 1.05M |
|---|
; A188732: Decimal expansion of (5+sqrt(61))/6.
; Submitted by Jon Maiga
; 2,1,3,5,0,4,1,6,1,2,6,5,1,1,0,9,0,6,5,6,8,8,2,8,7,1,2,2,6,2,6,5,1,6,9,0,2,2,6,1,3,8,4,1,8,9,4,4,1,4,2,7,2,1,6,6,9,6,2,0,7,2,9,3,3,6,5,1,3,0,9,3,1,4,8,9,4,5,4,5,0,9,0,7,0,9,0,5,5,0,8,7,1,1,1,6,7,4,8,2
mov $1,1
mov $3,$0
mul $3,4
lpb $3
add $1,$2
mul $1,$3
mul $2,$3
add $1,$2
mov $5,$0
max $5,1
div $1,$5
mul $5,2
div $2,$5
add $2,$1
div $1,6
sub $3,1
lpe
mov $4,10
pow $4,$0
add $1,$4
div $2,$4
cmp $6,0
add $2,$6
div $1,$2
mod $1,10
mov $0,$1
|
; void heap_info_unlocked(void *heap, void *callback)
SECTION code_alloc_malloc
PUBLIC heap_info_unlocked
EXTERN l0_heap_info_unlocked_callee
heap_info_unlocked:
pop af
pop de
pop bc
push bc
push de
push af
jp l0_heap_info_unlocked_callee
|
SFX_Fly_3_Ch1:
unknownnoise0x20 2, 241, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 161, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 209, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 129, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 177, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 97, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 145, 18
unknownnoise0x20 2, 0, 0
unknownnoise0x20 2, 65, 18
unknownnoise0x20 2, 0, 0
endchannel
|
ori $ra,$ra,0xf
ori $5,$6,34618
mthi $5
mfhi $4
mflo $1
mult $6,$6
lui $4,29084
mult $0,$2
mtlo $4
mtlo $5
sb $1,0($0)
divu $4,$ra
srav $0,$4,$4
mthi $0
mthi $1
srav $3,$5,$3
lui $2,27209
addiu $5,$2,4312
sll $6,$2,6
div $1,$ra
lui $0,60233
div $5,$ra
mflo $1
div $1,$ra
lb $1,15($0)
lui $1,41704
div $2,$ra
mfhi $0
mthi $5
addu $6,$4,$5
addu $0,$5,$1
mthi $0
mthi $5
ori $5,$4,23383
div $1,$ra
mtlo $5
mfhi $3
mtlo $5
div $1,$ra
sll $5,$5,28
mfhi $2
div $0,$ra
addu $3,$5,$3
mflo $1
mthi $6
mult $2,$0
mtlo $0
addu $4,$0,$3
ori $0,$5,65247
addu $6,$0,$6
lui $1,39563
addu $5,$1,$1
mtlo $5
multu $5,$4
divu $5,$ra
mthi $4
sll $1,$1,1
mthi $2
addu $0,$2,$4
mfhi $6
mflo $1
lb $1,5($0)
addiu $4,$6,-4329
ori $5,$5,6174
mtlo $1
mfhi $4
ori $4,$1,30935
sll $6,$4,26
lui $5,27417
lui $3,44174
ori $5,$4,48033
addu $3,$5,$3
addiu $4,$1,-19562
addu $2,$2,$2
multu $1,$2
srav $6,$4,$6
addiu $5,$4,20553
multu $5,$0
mult $2,$6
divu $6,$ra
mfhi $4
addu $6,$2,$2
sb $4,9($0)
divu $4,$ra
mthi $4
srav $6,$1,$3
mflo $4
lui $5,38595
sb $4,15($0)
srav $1,$1,$1
srav $4,$2,$3
mflo $4
ori $4,$3,50233
mfhi $0
div $4,$ra
ori $6,$2,17237
sb $1,8($0)
lb $3,6($0)
divu $5,$ra
ori $2,$2,51693
addu $5,$2,$1
sb $1,13($0)
multu $1,$2
mthi $0
srav $0,$4,$5
divu $5,$ra
mfhi $1
divu $0,$ra
ori $4,$6,36477
mult $2,$5
srav $2,$2,$5
addu $1,$3,$3
sll $2,$2,2
mult $2,$2
sll $0,$4,22
sb $5,12($0)
mflo $4
sll $0,$0,23
mflo $0
ori $4,$6,50902
addiu $3,$2,-11872
sb $3,11($0)
mthi $0
div $6,$ra
lb $5,9($0)
sll $1,$2,14
sll $4,$1,9
multu $5,$5
mult $4,$4
lb $6,1($0)
sll $1,$0,1
mflo $2
mtlo $4
lui $4,3461
mflo $1
mtlo $4
div $5,$ra
multu $1,$1
sb $1,10($0)
addu $4,$4,$2
div $3,$ra
mflo $2
divu $5,$ra
sll $6,$4,8
lui $5,64429
div $2,$ra
mthi $3
addu $2,$2,$2
mult $4,$1
sll $4,$1,21
srav $1,$4,$1
lui $1,64464
lb $4,6($0)
sb $4,16($0)
sll $5,$4,15
mult $4,$4
ori $6,$4,35531
multu $1,$1
sb $6,1($0)
mtlo $6
lb $4,11($0)
multu $1,$2
sb $3,3($0)
srav $0,$1,$3
mthi $1
addu $2,$1,$2
multu $5,$5
srav $0,$2,$0
mthi $1
addiu $1,$6,-14087
lui $1,14125
lb $0,14($0)
lui $4,52764
mthi $1
multu $5,$0
divu $6,$ra
mtlo $6
sb $1,12($0)
addiu $4,$4,-24185
ori $4,$2,2792
multu $4,$4
multu $4,$4
sll $4,$3,22
addu $4,$0,$2
lui $5,53947
mflo $5
ori $4,$0,9160
mthi $4
divu $5,$ra
ori $4,$1,19232
ori $1,$1,10538
divu $4,$ra
mtlo $4
addiu $1,$1,-23128
div $4,$ra
srav $1,$1,$2
divu $0,$ra
sb $5,7($0)
mult $4,$5
sll $1,$5,6
lb $1,4($0)
divu $4,$ra
sll $6,$6,1
divu $5,$ra
mfhi $5
sb $0,3($0)
mtlo $2
mthi $4
sll $4,$2,0
addu $4,$4,$4
mtlo $2
addu $2,$2,$2
lb $4,16($0)
sb $1,6($0)
divu $6,$ra
divu $6,$ra
addiu $2,$2,-22541
mtlo $2
lb $3,11($0)
sll $2,$2,30
mtlo $1
mflo $5
ori $6,$2,63191
ori $0,$0,9000
lb $5,7($0)
ori $4,$3,24593
mtlo $1
divu $3,$ra
mthi $5
div $4,$ra
mflo $2
ori $5,$1,59628
addiu $2,$2,2883
multu $2,$1
div $1,$ra
addiu $6,$4,18521
lui $1,61493
mtlo $1
ori $4,$2,25398
mtlo $1
mthi $1
mtlo $4
mfhi $4
lui $5,11813
ori $3,$2,40219
addu $5,$4,$4
mfhi $5
mult $1,$4
lb $5,16($0)
addu $4,$1,$4
addu $6,$1,$6
mfhi $5
addiu $5,$4,-24454
lb $1,8($0)
srav $6,$4,$6
sb $4,13($0)
mfhi $4
addiu $4,$0,21599
mtlo $4
mthi $5
mthi $4
addu $4,$2,$4
mtlo $4
ori $6,$4,7115
mfhi $5
multu $3,$1
addiu $4,$1,20262
div $4,$ra
mfhi $0
srav $4,$4,$5
sll $4,$4,6
mthi $1
ori $0,$1,2579
divu $0,$ra
mthi $1
mflo $2
ori $4,$1,5379
addu $1,$2,$1
mtlo $2
lb $4,12($0)
mfhi $6
ori $2,$2,64263
div $4,$ra
sll $0,$2,14
lb $0,14($0)
mfhi $4
srav $5,$4,$4
div $0,$ra
sll $4,$4,9
mtlo $4
mfhi $2
ori $4,$4,2877
lui $4,34159
ori $5,$5,46315
multu $1,$5
ori $0,$0,9380
addu $2,$2,$2
mfhi $4
div $5,$ra
sb $1,3($0)
lui $4,64594
mflo $1
addu $5,$5,$5
mthi $1
lb $3,4($0)
mult $1,$5
mfhi $4
mtlo $4
div $1,$ra
mult $1,$2
lui $0,47150
lb $5,0($0)
mtlo $2
div $1,$ra
lb $4,0($0)
addiu $1,$2,10512
ori $6,$6,24274
sll $1,$0,19
mflo $3
mtlo $2
lb $4,16($0)
mtlo $0
mfhi $3
lb $1,10($0)
divu $4,$ra
sll $1,$2,5
addu $6,$2,$6
srav $4,$4,$4
sll $4,$4,17
sb $4,12($0)
lui $2,45895
divu $0,$ra
div $5,$ra
mtlo $4
mthi $4
mthi $4
ori $0,$2,38357
divu $0,$ra
divu $5,$ra
lui $1,1727
multu $1,$5
lb $1,4($0)
ori $4,$5,58237
sb $1,1($0)
mtlo $4
mtlo $1
ori $5,$5,31481
mflo $1
sb $5,16($0)
sll $4,$2,7
addu $2,$2,$5
addiu $1,$4,4623
divu $5,$ra
mult $4,$6
mthi $2
mthi $0
div $4,$ra
mthi $2
ori $4,$4,47640
mult $4,$4
mult $5,$1
ori $4,$5,57390
mflo $6
lb $1,13($0)
addu $5,$5,$5
srav $3,$6,$3
lb $5,5($0)
srav $5,$0,$0
multu $1,$1
sll $4,$4,17
lui $1,43338
divu $4,$ra
lui $5,23090
div $4,$ra
sll $4,$4,1
divu $4,$ra
multu $2,$4
divu $0,$ra
sll $2,$2,18
mfhi $0
lui $1,22086
sll $2,$4,11
srav $1,$2,$2
lb $5,1($0)
ori $3,$5,27494
mflo $2
lb $1,2($0)
divu $5,$ra
divu $4,$ra
lui $1,61992
sll $0,$0,23
lui $4,29089
addiu $3,$2,13564
lui $5,3871
div $6,$ra
srav $0,$0,$2
lb $1,1($0)
mthi $6
mult $0,$4
sb $5,6($0)
mtlo $0
div $4,$ra
mfhi $2
mflo $3
div $0,$ra
mtlo $4
divu $1,$ra
mtlo $3
div $2,$ra
mult $0,$5
div $5,$ra
div $5,$ra
addiu $5,$5,13803
divu $4,$ra
div $4,$ra
lui $0,13505
lui $4,32689
mult $0,$0
multu $5,$5
srav $1,$2,$1
mult $1,$2
div $0,$ra
div $4,$ra
lui $0,37161
mtlo $1
addu $6,$4,$6
mfhi $3
sb $5,16($0)
mult $2,$0
multu $4,$4
sb $5,14($0)
mtlo $4
mthi $1
mthi $1
multu $4,$1
mthi $2
mthi $5
lui $4,62200
multu $2,$2
multu $4,$1
lui $5,56106
sll $5,$5,27
addiu $6,$1,-23551
lb $5,14($0)
divu $3,$ra
lui $3,23971
addu $5,$2,$3
div $4,$ra
addu $2,$2,$3
srav $2,$2,$2
divu $5,$ra
ori $5,$1,20561
mthi $5
mtlo $3
multu $4,$4
addiu $4,$2,12368
sll $4,$2,30
srav $0,$2,$2
lb $2,12($0)
divu $1,$ra
mflo $4
ori $4,$3,20536
mult $0,$5
mfhi $2
sll $2,$2,31
divu $6,$ra
mfhi $4
mthi $1
addu $1,$5,$5
mult $2,$2
mthi $2
lb $6,3($0)
lb $4,10($0)
ori $5,$5,8145
addiu $2,$2,1322
addiu $0,$4,14197
mult $4,$4
mfhi $5
ori $5,$2,65192
lb $1,11($0)
addiu $6,$0,4527
mthi $0
ori $6,$0,42128
lb $4,5($0)
multu $1,$1
div $4,$ra
sb $4,10($0)
lb $0,3($0)
ori $4,$2,45282
mfhi $4
multu $4,$1
divu $4,$ra
mtlo $4
sb $4,12($0)
multu $4,$4
sll $4,$5,28
sb $4,1($0)
mfhi $4
mtlo $1
addiu $4,$4,17505
addu $1,$1,$1
sll $4,$4,3
mflo $0
mthi $1
addiu $4,$2,13335
srav $0,$2,$2
mfhi $1
lb $1,1($0)
ori $4,$4,27114
ori $4,$2,64520
sb $4,2($0)
mthi $4
lb $4,13($0)
div $5,$ra
lb $0,16($0)
divu $1,$ra
ori $1,$4,1895
multu $1,$3
divu $6,$ra
divu $2,$ra
ori $2,$5,46890
lb $1,1($0)
ori $3,$6,48091
mthi $5
multu $1,$2
lui $5,8228
addu $5,$2,$2
mfhi $0
mflo $1
addiu $5,$3,16382
lb $4,10($0)
divu $4,$ra
sll $1,$5,16
addiu $5,$2,10206
ori $5,$4,7405
addu $2,$2,$2
mtlo $0
sll $5,$6,24
mflo $2
lb $1,5($0)
multu $5,$1
multu $1,$4
multu $0,$0
mflo $4
div $4,$ra
multu $4,$5
addiu $5,$1,30687
lui $5,57402
sll $4,$2,26
srav $2,$2,$0
mfhi $1
mtlo $1
sll $6,$5,5
mult $1,$4
sll $4,$6,22
addu $4,$4,$3
addu $2,$6,$2
div $2,$ra
lb $0,2($0)
ori $4,$0,29595
sb $2,3($0)
mtlo $1
sb $0,0($0)
lui $5,59876
srav $4,$4,$4
lb $4,3($0)
mult $1,$1
mthi $4
multu $2,$2
mthi $5
srav $4,$4,$2
div $0,$ra
srav $0,$1,$0
sll $6,$2,28
divu $6,$ra
addu $5,$0,$5
mtlo $3
addiu $5,$1,14988
srav $6,$5,$1
mult $0,$1
mtlo $2
addu $6,$4,$2
addu $5,$6,$4
divu $5,$ra
mult $5,$5
ori $2,$2,15239
sll $4,$4,23
mtlo $6
sll $1,$4,18
multu $4,$1
divu $1,$ra
lui $4,55634
mtlo $4
multu $4,$0
ori $4,$1,32989
addiu $0,$3,-12768
divu $5,$ra
mult $6,$2
mthi $5
mflo $5
mflo $2
multu $6,$2
lui $4,29570
mult $4,$4
divu $4,$ra
addiu $3,$3,-26514
multu $2,$2
lui $4,8040
mtlo $1
lb $2,0($0)
mthi $6
sll $5,$4,27
mult $1,$1
divu $1,$ra
mflo $5
ori $5,$1,25364
lb $5,2($0)
mtlo $2
sll $2,$2,0
ori $6,$6,41133
srav $0,$5,$0
mfhi $5
mtlo $4
lb $4,5($0)
multu $2,$2
mthi $3
addu $0,$0,$0
mfhi $4
addu $4,$6,$4
lui $3,59235
addu $4,$4,$4
addiu $2,$2,3437
addiu $4,$4,12251
lui $2,1973
sb $5,12($0)
addu $0,$5,$0
mflo $4
sb $1,6($0)
lui $4,47137
multu $0,$2
addu $4,$5,$3
mthi $0
div $2,$ra
addiu $4,$4,2255
divu $2,$ra
sb $1,4($0)
srav $4,$2,$4
mult $4,$4
mtlo $4
sb $5,13($0)
ori $1,$4,28248
mflo $5
sb $5,10($0)
mult $4,$4
mult $4,$4
addu $6,$6,$6
addiu $1,$5,-21523
mult $1,$3
addu $5,$2,$4
addu $4,$1,$3
divu $4,$ra
div $5,$ra
lb $5,0($0)
divu $5,$ra
addu $1,$2,$5
div $5,$ra
mthi $4
addiu $4,$4,31303
srav $5,$1,$2
lb $5,2($0)
srav $1,$1,$1
ori $4,$2,52235
lui $1,85
mult $3,$2
lui $0,10270
ori $4,$5,19383
lui $5,14800
lb $2,8($0)
lb $4,12($0)
lui $0,47655
multu $4,$1
mtlo $1
mthi $4
lui $4,8878
mult $1,$1
multu $0,$6
mthi $0
divu $5,$ra
addiu $4,$6,11852
mfhi $1
div $0,$ra
ori $5,$2,31990
ori $1,$2,9264
addiu $2,$6,29609
ori $6,$5,44393
mtlo $4
sll $5,$2,30
addu $2,$2,$2
lui $4,19785
srav $1,$4,$2
multu $0,$0
srav $5,$6,$1
divu $4,$ra
addiu $4,$2,31228
addiu $5,$4,-14613
sb $2,9($0)
mfhi $5
mthi $4
mflo $4
mflo $6
div $2,$ra
addiu $1,$4,12218
sll $6,$4,31
sll $6,$1,23
mfhi $4
mflo $0
mtlo $4
div $6,$ra
divu $6,$ra
multu $4,$5
divu $5,$ra
lb $0,12($0)
addiu $4,$1,-3619
addiu $5,$5,-20380
ori $2,$2,49706
ori $5,$5,56935
addu $1,$2,$5
sll $5,$4,23
addu $4,$4,$4
sb $4,11($0)
mtlo $1
srav $4,$4,$4
srav $5,$4,$5
divu $6,$ra
mtlo $4
addu $0,$0,$4
divu $0,$ra
mthi $4
lui $1,64325
srav $4,$1,$2
lui $1,7957
mthi $1
addiu $1,$4,-32313
mult $0,$1
sll $4,$2,3
lb $2,11($0)
mult $3,$3
mflo $5
multu $2,$2
mtlo $1
addu $1,$4,$4
ori $0,$4,51376
mfhi $1
addiu $1,$5,30239
div $0,$ra
lb $5,8($0)
mult $4,$4
sll $4,$0,15
addiu $4,$3,-24502
addu $4,$2,$4
divu $6,$ra
addu $0,$2,$2
mtlo $0
mthi $2
lui $1,35376
srav $5,$3,$3
sll $4,$4,30
lb $1,11($0)
div $2,$ra
multu $4,$2
mthi $1
addiu $5,$2,-16131
addiu $3,$3,14546
lb $2,13($0)
mflo $6
srav $1,$6,$5
lui $4,60417
multu $3,$4
mflo $4
mult $2,$2
ori $0,$5,6830
srav $4,$4,$1
sll $4,$1,13
divu $6,$ra
addu $3,$3,$3
srav $5,$1,$4
lui $1,30861
mfhi $4
mthi $5
lui $3,23200
sb $5,7($0)
lb $4,13($0)
mtlo $1
lui $5,39447
mflo $2
mthi $4
mflo $1
mtlo $6
divu $4,$ra
addu $5,$4,$1
sb $5,8($0)
div $4,$ra
mtlo $1
mtlo $4
lb $1,1($0)
sb $4,6($0)
multu $1,$1
mfhi $1
divu $5,$ra
mult $4,$2
sb $3,14($0)
div $5,$ra
addu $1,$2,$3
lb $2,14($0)
addiu $1,$4,6491
multu $6,$5
mfhi $5
srav $1,$1,$1
mfhi $5
mtlo $2
addiu $0,$5,16782
multu $3,$4
addiu $4,$4,-20784
lb $0,1($0)
mtlo $0
lui $5,24102
div $1,$ra
mthi $3
divu $3,$ra
lui $0,41213
mult $0,$2
sll $2,$2,30
addiu $5,$2,22669
mthi $2
addu $5,$2,$0
div $1,$ra
ori $5,$4,41124
multu $5,$2
mfhi $4
multu $4,$4
sll $1,$5,17
mtlo $3
addu $5,$4,$5
addu $4,$1,$1
mthi $1
mflo $5
lui $6,27878
mflo $4
multu $2,$5
mult $6,$5
divu $4,$ra
lui $0,64743
mflo $2
sb $1,5($0)
addu $4,$4,$2
ori $0,$0,14148
lb $4,5($0)
srav $6,$2,$6
multu $5,$4
multu $5,$6
mtlo $4
addu $3,$3,$3
div $4,$ra
mfhi $5
divu $2,$ra
mflo $4
mult $5,$2
div $5,$ra
mtlo $5
addu $5,$6,$4
multu $1,$1
multu $4,$4
ori $5,$5,20019
sb $5,11($0)
mfhi $4
lb $4,4($0)
multu $4,$2
multu $6,$4
ori $4,$5,37944
mthi $5
mflo $4
ori $4,$5,64523
mult $5,$4
mult $4,$6
mflo $2
ori $1,$2,61449
addu $4,$4,$4
mthi $5
div $4,$ra
|
//
// Add --log_level=message to see the messages!
//
#define BOOST_TEST_MODULE "Layer Updaters Tests"
#include <boost/test/unit_test.hpp>
#include <sstream>
#include "core/types.h"
#include "core/utils.h"
#include "core/updaters.h"
#include "test_utils.h"
#include "timer.h"
#include "mnist_test.h"
using namespace std;
using namespace boost;
using namespace boost::unit_test;
using namespace yann;
using namespace yann::test;
struct UpdatersTestFixture
{
UpdatersTestFixture()
{
}
~UpdatersTestFixture()
{
}
}; // struct UpdatersTestFixture
BOOST_FIXTURE_TEST_SUITE(UpdatersTest, UpdatersTestFixture);
BOOST_AUTO_TEST_CASE(Test_GradientDescent_Matrix)
{
BOOST_TEST_MESSAGE("*** Updater_GradientDescent Matrix test ...");
const MatrixSize size = 2;
auto updater = make_unique<Updater_GradientDescent>(0.9, 0.1);
BOOST_CHECK(updater);
updater->init(size, size);
updater->start_epoch();
Matrix ww(size, size);
Matrix ww_expected(size, size);
Matrix delta(size, size);
// test decay factor
ww << 1, 2, 3, 4;
delta << 0.0, 0.0, 0.0, 0.0;
ww_expected << 0.9, 1.8, 2.7, 3.6;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
// test learning + decay factor
ww << 1, 2, 3, 4;
delta << 0.1, 0.2, 0.3, 0.4;
ww_expected << 0.81, 1.62, 2.43, 3.24;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Test_GradientDescent_Value)
{
BOOST_TEST_MESSAGE("*** Updater_GradientDescent value test ...");
auto updater = make_unique<Updater_GradientDescent>(0.9, 0.1);
BOOST_CHECK(updater);
updater->init(1, 1);
updater->start_epoch();
Value ww;
Value ww_expected;
Value delta;
// test decay factor
ww = 1;
delta = 0.0;
ww_expected = 0.9;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
// test learning + decay factor
ww = 1;
delta = 0.1;
ww_expected = 0.81;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
}
BOOST_AUTO_TEST_CASE(Test_GradientDescentWithMomentum_Matrix)
{
BOOST_TEST_MESSAGE("*** Updater_GradientDescentWithMomentum matrix test ...");
const MatrixSize size = 2;
auto updater = make_unique<Updater_GradientDescentWithMomentum>(0.7, 0.9);
BOOST_CHECK(updater);
updater->init(size, size);
updater->start_epoch();
Matrix ww(size, size);
Matrix ww_expected(size, size);
Matrix delta(size, size);
// first iteration
// v(0) = 0,0,0,0
ww << 1, 2, 3, 4;
delta << 0.1, 0.2, 0.3, 0.4;
// v(1) = 0.01, 0.02, 0.03, 0.04
ww_expected << 0.993, 1.986, 2.979, 3.972;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
// second iteration
delta << 0.4, 0.3, 0.2, 0.1;
// v(2) = 0.049, 0.048, 0.047, 0.046
ww_expected << 0.9587, 1.9524, 2.9461, 3.9398;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Test_GradientDescentWithMomentum_Value)
{
BOOST_TEST_MESSAGE("*** Updater_GradientDescentWithMomentum value test ...");
auto updater = make_unique<Updater_GradientDescentWithMomentum>(0.7, 0.9);
BOOST_CHECK(updater);
updater->init(1, 1);
updater->start_epoch();
Value ww;
Value ww_expected;
Value delta;
// first iteration
// v(0) = 0
ww = 1;
delta = 0.1;
// v(1) = 0.01
ww_expected = 0.993;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
// second iteration
delta = 0.4;
// v(2) = 0.049
ww_expected = 0.9587;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
}
BOOST_AUTO_TEST_CASE(Test_AdaGrad_Matrix)
{
BOOST_TEST_MESSAGE("*** Updater_AdaGrad matrix test ...");
const MatrixSize size = 2;
auto updater = make_unique<Updater_AdaGrad>(0.01, 1.0e-07);
BOOST_CHECK(updater);
updater->init(size, size);
updater->start_epoch();
Matrix ww(size, size);
Matrix ww_expected(size, size);
Matrix delta(size, size);
// first iteration
// s(0) = 0,0,0,0
ww << 1, 2, 3, 4;
delta << 0.1, 0.2, 0.3, 0.4;
// s(1) = 0.01, 0.04, 0.09, 0.16
ww_expected << 0.99, 1.99, 2.99, 3.99;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
// second iteration
delta << 0.4, 0.3, 0.2, 0.1;
// s(2) = 0.17, 0.13, 0.13, 0.17
ww_expected << 0.9803, 1.9817, 2.9845, 3.9876;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Test_AdaGrad_Value)
{
BOOST_TEST_MESSAGE("*** Updater_AdaGrad value test ...");
auto updater = make_unique<Updater_AdaGrad>(0.01, 1.0e-07);
BOOST_CHECK(updater);
updater->init(1, 1);
updater->start_epoch();
Value ww;
Value ww_expected;
Value delta;
// first iteration
// s(0) = 0
ww = 1;
delta = 0.1;
// s(1) = 0.01
ww_expected = 0.99;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
// second iteration
delta = 0.4;
// s(2) = 0.17
ww_expected = 0.9803;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
}
BOOST_AUTO_TEST_CASE(Test_RMSprop_Matrix)
{
BOOST_TEST_MESSAGE("*** Updater_RMSprop matrix test ...");
const MatrixSize size = 2;
auto updater = make_unique<Updater_RMSprop>(0.01, 0.9, 1.0e-07);
BOOST_CHECK(updater);
updater->init(size, size);
updater->start_epoch();
Matrix ww(size, size);
Matrix ww_expected(size, size);
Matrix delta(size, size);
// first iteration
ww << 1, 2, 3, 4;
delta << 0.1, 0.2, 0.3, 0.4;
ww_expected << 0.9683788044, 1.968377619, 2.968377399, 3.968377322;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
// second iteration
delta << 0.4, 0.3, 0.2, 0.1;
ww_expected << 0.9376096647, 1.941651601, 2.950195656, 3.960319119;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Test_RMSprop_Value)
{
BOOST_TEST_MESSAGE("*** Updater_RMSprop value test ...");
auto updater = make_unique<Updater_RMSprop>(0.01, 0.9, 1.0e-07);
BOOST_CHECK(updater);
updater->init(1, 1);
updater->start_epoch();
Value ww;
Value ww_expected;
Value delta;
// first iteration
// s(0) = 0
ww = 1;
delta = 0.1;
// s(1) = 0.001
ww_expected = 0.9683788044;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
// second iteration
delta = 0.4;
// s(2) = 0.0169
ww_expected = 0.9376096647;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
}
BOOST_AUTO_TEST_CASE(Test_AdaDelta_Matrix)
{
BOOST_TEST_MESSAGE("*** Updater_AdaDelta matrix test ...");
const MatrixSize size = 2;
auto updater = make_unique<Updater_AdaDelta>(0.95, 1.0e-07);
BOOST_CHECK(updater);
updater->init(size, size);
updater->start_epoch();
Matrix ww(size, size);
Matrix ww_expected(size, size);
Matrix delta(size, size);
// first iteration
// s(0) = 0, 0, 0, 0
// d(0) = 0, 0, 0, 0
ww << 1, 2, 3, 4;
delta << 1, 2, -1, -2;
// s(1) = 0.05, 0.2, 0.05, 0.2
// d(1) = 0, 0, 0, 0
ww_expected << 0.9986, 1.9986, 3.0014, 4.0014;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
// second iteration
delta << 1, 2, -1, -2;
// s(2) = 0.0975, 0.39, 0.0975, 0.39
// d(2) = 0.0000000999998, 0.00000009999995, 0.0000000999998, 0.00000009999995
ww_expected << 0.9971535596, 1.997153557, 3.00284644, 4.002846443;
updater->update(delta, 1, ww);
BOOST_CHECK(ww_expected.isApprox(ww, TEST_TOLERANCE));
}
BOOST_AUTO_TEST_CASE(Test_AdaDelta_Value)
{
BOOST_TEST_MESSAGE("*** Updater_AdaDelta value test ...");
auto updater = make_unique<Updater_AdaDelta>(0.95, 1.0e-07);
BOOST_CHECK(updater);
updater->init(1, 1);
updater->start_epoch();
Value ww;
Value ww_expected;
Value delta;
// first iteration
// s(0) = 0
// d(0) = 0
ww = 1;
delta = 1;
// s(1) = 0.05
// d(1) = 0
ww_expected = 0.9985857879;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
// second iteration
delta = 1;
// s(2) = 0.0975
// d(2) = 0.0000000999998
ww_expected = 0.9971535596;
updater->update(delta, 1, ww);
BOOST_CHECK_CLOSE(ww_expected, ww, TEST_TOLERANCE);
}
BOOST_AUTO_TEST_SUITE_END()
|
; A051494: Expansion of (1 - x + x^2 + x^3)/(1 - x^2)^3.
; 1,-1,4,-2,9,-3,16,-4,25,-5,36,-6,49,-7,64,-8,81,-9,100,-10,121,-11,144,-12,169,-13,196,-14,225,-15,256,-16,289,-17,324,-18,361,-19,400,-20,441,-21,484,-22,529,-23,576,-24,625,-25,676,-26,729,-27,784,-28,841,-29,900,-30,961,-31,1024,-32,1089,-33,1156,-34,1225,-35,1296,-36,1369,-37,1444,-38,1521,-39,1600,-40,1681,-41,1764,-42,1849,-43,1936,-44,2025,-45,2116,-46,2209,-47,2304,-48,2401,-49,2500,-50
mov $1,2
add $1,$0
div $1,-2
mov $2,$0
gcd $2,2
pow $1,$2
mov $0,$1
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r11
push %r12
push %r13
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WC_ht+0x17b5e, %r11
nop
nop
cmp $64876, %rdi
mov (%r11), %r12w
nop
nop
nop
nop
nop
dec %rbp
lea addresses_UC_ht+0xfee6, %r10
nop
inc %rsi
mov $0x6162636465666768, %rbp
movq %rbp, %xmm6
movups %xmm6, (%r10)
nop
xor %rdi, %rdi
lea addresses_WT_ht+0x1775e, %rsi
lea addresses_WC_ht+0x1c21e, %rdi
clflush (%rsi)
nop
nop
xor %r13, %r13
mov $35, %rcx
rep movsl
nop
nop
nop
nop
nop
xor %rbp, %rbp
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r13
pop %r12
pop %r11
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r13
push %r14
push %r8
push %rax
push %rbx
push %rcx
push %rdi
push %rsi
// Store
lea addresses_D+0x755e, %r10
nop
add $59992, %rbx
movl $0x51525354, (%r10)
and $23196, %r14
// Store
lea addresses_UC+0x1fd5e, %r14
nop
nop
nop
and $60813, %r13
mov $0x5152535455565758, %rax
movq %rax, (%r14)
nop
cmp $37035, %rbx
// Store
lea addresses_WT+0xdb5e, %r8
inc %rcx
mov $0x5152535455565758, %rax
movq %rax, %xmm0
movups %xmm0, (%r8)
nop
nop
sub %r14, %r14
// Store
lea addresses_A+0x1245e, %r14
nop
nop
nop
nop
nop
and %rcx, %rcx
mov $0x5152535455565758, %rbx
movq %rbx, (%r14)
nop
nop
nop
nop
inc %rax
// Store
lea addresses_WC+0x840e, %r14
nop
nop
nop
inc %rcx
mov $0x5152535455565758, %r13
movq %r13, %xmm3
vmovups %ymm3, (%r14)
nop
nop
inc %rcx
// Store
lea addresses_A+0x835e, %r14
and %r13, %r13
mov $0x5152535455565758, %r8
movq %r8, (%r14)
nop
nop
nop
nop
nop
add %rax, %rax
// Store
lea addresses_PSE+0xd15e, %r8
xor $48085, %r13
mov $0x5152535455565758, %r10
movq %r10, %xmm7
vmovups %ymm7, (%r8)
nop
nop
add %rbx, %rbx
// Store
lea addresses_PSE+0x1aa37, %rbx
nop
inc %r14
movw $0x5152, (%rbx)
nop
nop
nop
nop
sub $64121, %r13
// REPMOV
lea addresses_normal+0xa7c2, %rsi
lea addresses_WC+0x163fe, %rdi
nop
nop
nop
nop
nop
xor $53533, %r13
mov $45, %rcx
rep movsw
nop
nop
cmp $26205, %r14
// Faulty Load
lea addresses_PSE+0x1575e, %rax
clflush (%rax)
xor %r14, %r14
mov (%rax), %r10w
lea oracles, %rcx
and $0xff, %r10
shlq $12, %r10
mov (%rcx,%r10,1), %r10
pop %rsi
pop %rdi
pop %rcx
pop %rbx
pop %rax
pop %r8
pop %r14
pop %r13
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 0}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_D', 'AVXalign': False, 'size': 4, 'NT': False, 'same': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC', 'AVXalign': False, 'size': 8, 'NT': True, 'same': False, 'congruent': 7}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WC', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 3}}
{'OP': 'STOR', 'dst': {'type': 'addresses_A', 'AVXalign': False, 'size': 8, 'NT': False, 'same': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 32, 'NT': False, 'same': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 0}}
{'src': {'type': 'addresses_normal', 'congruent': 2, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC', 'congruent': 5, 'same': False}}
[Faulty Load]
{'src': {'type': 'addresses_PSE', 'AVXalign': False, 'size': 2, 'NT': False, 'same': True, 'congruent': 0}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WC_ht', 'AVXalign': False, 'size': 2, 'NT': False, 'same': False, 'congruent': 8}, 'OP': 'LOAD'}
{'OP': 'STOR', 'dst': {'type': 'addresses_UC_ht', 'AVXalign': False, 'size': 16, 'NT': False, 'same': False, 'congruent': 3}}
{'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'OP': 'REPM', 'dst': {'type': 'addresses_WC_ht', 'congruent': 5, 'same': True}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
-- 7 Billion Humans (2053) --
-- 2: Welcome, New Employees --
-- Author: soerface
-- Size: 3
-- Speed: 1
step s
pickup c
drop
|
// dear imgui, v1.68 WIP
// (main code and documentation)
// Call and read ImGui::ShowDemoWindow() in imgui_demo.cpp for demo code.
// Newcomers, read 'Programmer guide' below for notes on how to setup Dear ImGui in your codebase.
// Get latest version at https://github.com/ocornut/imgui
// Releases change-log at https://github.com/ocornut/imgui/releases
// Technical Support for Getting Started https://discourse.dearimgui.org/c/getting-started
// Gallery (please post your screenshots/video there!): https://github.com/ocornut/imgui/issues/1269
// Developed by Omar Cornut and every direct or indirect contributors to the GitHub.
// See LICENSE.txt for copyright and licensing details (standard MIT License).
// This library is free but I need your support to sustain development and maintenance.
// Businesses: you can support continued maintenance and development via support contracts or sponsoring, see docs/README.
// Individuals: you can support continued maintenance and development via donations or Patreon https://www.patreon.com/imgui.
// It is recommended that you don't modify imgui.cpp! It will become difficult for you to update the library.
// Note that 'ImGui::' being a namespace, you can add functions into the namespace from your own source files, without
// modifying imgui.h or imgui.cpp. You may include imgui_internal.h to access internal data structures, but it doesn't
// come with any guarantee of forward compatibility. Discussing your changes on the GitHub Issue Tracker may lead you
// to a better solution or official support for them.
/*
Index of this file:
DOCUMENTATION
- MISSION STATEMENT
- END-USER GUIDE
- PROGRAMMER GUIDE (read me!)
- Read first.
- How to update to a newer version of Dear ImGui.
- Getting started with integrating Dear ImGui in your code/engine.
- This is how a simple application may look like (2 variations).
- This is how a simple rendering function may look like.
- Using gamepad/keyboard navigation controls.
- API BREAKING CHANGES (read me when you update!)
- FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
- How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
- How can I display an image? What is ImTextureID, how does it works?
- How can I have multiple widgets with the same label or with an empty label? A primer on labels and the ID Stack.
- How can I use my own math types instead of ImVec2/ImVec4?
- How can I load a different font than the default?
- How can I easily use icons in my application?
- How can I load multiple fonts?
- How can I display and input non-latin characters such as Chinese, Japanese, Korean, Cyrillic?
- How can I interact with standard C++ types (such as std::string and std::vector)?
- How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
- How can I use Dear ImGui on a platform that doesn't have a mouse or a keyboard? (input share, remoting, gamepad)
- I integrated Dear ImGui in my engine and the text or lines are blurry..
- I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
- How can I help?
CODE
(search for "[SECTION]" in the code to find them)
// [SECTION] FORWARD DECLARATIONS
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
// [SECTION] MISC HELPER/UTILITIES (ImText* functions)
// [SECTION] MISC HELPER/UTILITIES (Color functions)
// [SECTION] ImGuiStorage
// [SECTION] ImGuiTextFilter
// [SECTION] ImGuiTextBuffer
// [SECTION] ImGuiListClipper
// [SECTION] RENDER HELPERS
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
// [SECTION] TOOLTIPS
// [SECTION] POPUPS
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
// [SECTION] COLUMNS
// [SECTION] DRAG AND DROP
// [SECTION] DOCKING
// [SECTION] LOGGING/CAPTURING
// [SECTION] SETTINGS
// [SECTION] PLATFORM DEPENDENT HELPERS
// [SECTION] METRICS/DEBUG WINDOW
*/
//-----------------------------------------------------------------------------
// DOCUMENTATION
//-----------------------------------------------------------------------------
/*
MISSION STATEMENT
=================
- Easy to use to create code-driven and data-driven tools.
- Easy to use to create ad hoc short-lived tools and long-lived, more elaborate tools.
- Easy to hack and improve.
- Minimize screen real-estate usage.
- Minimize setup and maintenance.
- Minimize state storage on user side.
- Portable, minimize dependencies, run on target (consoles, phones, etc.).
- Efficient runtime and memory consumption (NB- we do allocate when "growing" content e.g. creating a window,.
opening a tree node for the first time, etc. but a typical frame should not allocate anything).
Designed for developers and content-creators, not the typical end-user! Some of the weaknesses includes:
- Doesn't look fancy, doesn't animate.
- Limited layout features, intricate layouts are typically crafted in code.
END-USER GUIDE
==============
- Double-click on title bar to collapse window.
- Click upper right corner to close a window, available when 'bool* p_open' is passed to ImGui::Begin().
- Click and drag on lower right corner to resize window (double-click to auto fit window to its contents).
- Click and drag on any empty space to move window.
- TAB/SHIFT+TAB to cycle through keyboard editable fields.
- CTRL+Click on a slider or drag box to input value as text.
- Use mouse wheel to scroll.
- Text editor:
- Hold SHIFT or use mouse to select text.
- CTRL+Left/Right to word jump.
- CTRL+Shift+Left/Right to select words.
- CTRL+A our Double-Click to select all.
- CTRL+X,CTRL+C,CTRL+V to use OS clipboard/
- CTRL+Z,CTRL+Y to undo/redo.
- ESCAPE to revert text to its original value.
- You can apply arithmetic operators +,*,/ on numerical values. Use +- to subtract (because - would set a negative value!)
- Controls are automatically adjusted for OSX to match standard OSX text editing operations.
- General Keyboard controls: enable with ImGuiConfigFlags_NavEnableKeyboard.
- General Gamepad controls: enable with ImGuiConfigFlags_NavEnableGamepad. See suggested mappings in imgui.h ImGuiNavInput_ + download PNG/PSD at http://goo.gl/9LgVZW
PROGRAMMER GUIDE
================
READ FIRST:
- Read the FAQ below this section!
- Your code creates the UI, if your code doesn't run the UI is gone! The UI can be highly dynamic, there are no construction
or destruction steps, less superfluous data retention on your side, less state duplication, less state synchronization, less bugs.
- Call and read ImGui::ShowDemoWindow() for demo code demonstrating most features.
- The library is designed to be built from sources. Avoid pre-compiled binaries and packaged versions. See imconfig.h to configure your build.
- Dear ImGui is an implementation of the IMGUI paradigm (immediate-mode graphical user interface, a term coined by Casey Muratori).
You can learn about IMGUI principles at http://www.johno.se/book/imgui.html, http://mollyrocket.com/861 & more links docs/README.md.
- Dear ImGui is a "single pass" rasterizing implementation of the IMGUI paradigm, aimed at ease of use and high-performances.
For every application frame your UI code will be called only once. This is in contrast to e.g. Unity's own implementation of an IMGUI,
where the UI code is called multiple times ("multiple passes") from a single entry point. There are pros and cons to both approaches.
- Our origin are on the top-left. In axis aligned bounding boxes, Min = top-left, Max = bottom-right.
- This codebase is also optimized to yield decent performances with typical "Debug" builds settings.
- Please make sure you have asserts enabled (IM_ASSERT redirects to assert() by default, but can be redirected).
If you get an assert, read the messages and comments around the assert.
- C++: this is a very C-ish codebase: we don't rely on C++11, we don't include any C++ headers, and ImGui:: is a namespace.
- C++: ImVec2/ImVec4 do not expose math operators by default, because it is expected that you use your own math types.
See FAQ "How can I use my own math types instead of ImVec2/ImVec4?" for details about setting up imconfig.h for that.
However, imgui_internal.h can optionally export math operators for ImVec2/ImVec4, which we use in this codebase.
- C++: pay attention that ImVector<> manipulates plain-old-data and does not honor construction/destruction (avoid using it in your code!).
HOW TO UPDATE TO A NEWER VERSION OF DEAR IMGUI:
- Overwrite all the sources files except for imconfig.h (if you have made modification to your copy of imconfig.h)
- Or maintain your own branch where you have imconfig.h modified.
- Read the "API BREAKING CHANGES" section (below). This is where we list occasional API breaking changes.
If a function/type has been renamed / or marked obsolete, try to fix the name in your code before it is permanently removed
from the public API. If you have a problem with a missing function/symbols, search for its name in the code, there will
likely be a comment about it. Please report any issue to the GitHub page!
- Try to keep your copy of dear imgui reasonably up to date.
GETTING STARTED WITH INTEGRATING DEAR IMGUI IN YOUR CODE/ENGINE:
- Run and study the examples and demo in imgui_demo.cpp to get acquainted with the library.
- Add the Dear ImGui source files to your projects or using your preferred build system.
It is recommended you build and statically link the .cpp files as part of your project and not as shared library (DLL).
- You can later customize the imconfig.h file to tweak some compile-time behavior, such as integrating imgui types with your own maths types.
- When using Dear ImGui, your programming IDE is your friend: follow the declaration of variables, functions and types to find comments about them.
- Dear ImGui never touches or knows about your GPU state. The only function that knows about GPU is the draw function that you provide.
Effectively it means you can create widgets at any time in your code, regardless of considerations of being in "update" vs "render"
phases of your own application. All rendering informatioe are stored into command-lists that you will retrieve after calling ImGui::Render().
- Refer to the bindings and demo applications in the examples/ folder for instruction on how to setup your code.
- If you are running over a standard OS with a common graphics API, you should be able to use unmodified imgui_impl_*** files from the examples/ folder.
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 1: USING THE EXAMPLE BINDINGS (imgui_impl_XXX.cpp files from the examples/ folder).
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Initialize helper Platform and Renderer bindings (here we are using imgui_impl_win32 and imgui_impl_dx11)
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX11_Init(g_pd3dDevice, g_pd3dDeviceContext);
// Application main loop
while (true)
{
// Feed inputs to dear imgui, start new frame
ImGui_ImplDX11_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
// Any application code here
ImGui::Text("Hello, world!");
// Render dear imgui into screen
ImGui::Render();
ImGui_ImplDX11_RenderDrawData(ImGui::GetDrawData());
g_pSwapChain->Present(1, 0);
}
// Shutdown
ImGui_ImplDX11_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
HOW A SIMPLE APPLICATION MAY LOOK LIKE:
EXHIBIT 2: IMPLEMENTING CUSTOM BINDING / CUSTOM ENGINE.
// Application init: create a dear imgui context, setup some options, load fonts
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
// TODO: Set optional io.ConfigFlags values, e.g. 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard' to enable keyboard controls.
// TODO: Fill optional fields of the io structure later.
// TODO: Load TTF/OTF fonts if you don't want to use the default font.
// Build and load the texture atlas into a texture
// (In the examples/ app this is usually done within the ImGui_ImplXXX_Init() function from one of the demo Renderer)
int width, height;
unsigned char* pixels = NULL;
io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height);
// At this point you've got the texture data and you need to upload that your your graphic system:
// After we have created the texture, store its pointer/identifier (_in whichever format your engine uses_) in 'io.Fonts->TexID'.
// This will be passed back to your via the renderer. Basically ImTextureID == void*. Read FAQ below for details about ImTextureID.
MyTexture* texture = MyEngine::CreateTextureFromMemoryPixels(pixels, width, height, TEXTURE_TYPE_RGBA32)
io.Fonts->TexID = (void*)texture;
// Application main loop
while (true)
{
// Setup low-level inputs, e.g. on Win32: calling GetKeyboardState(), or write to those fields from your Windows message handlers, etc.
// (In the examples/ app this is usually done within the ImGui_ImplXXX_NewFrame() function from one of the demo Platform bindings)
io.DeltaTime = 1.0f/60.0f; // set the time elapsed since the previous frame (in seconds)
io.DisplaySize.x = 1920.0f; // set the current display width
io.DisplaySize.y = 1280.0f; // set the current display height here
io.MousePos = my_mouse_pos; // set the mouse position
io.MouseDown[0] = my_mouse_buttons[0]; // set the mouse button states
io.MouseDown[1] = my_mouse_buttons[1];
// Call NewFrame(), after this point you can use ImGui::* functions anytime
// (So you want to try calling NewFrame() as early as you can in your mainloop to be able to use imgui everywhere)
ImGui::NewFrame();
// Most of your application code here
ImGui::Text("Hello, world!");
MyGameUpdate(); // may use any ImGui functions, e.g. ImGui::Begin("My window"); ImGui::Text("Hello, world!"); ImGui::End();
MyGameRender(); // may use any ImGui functions as well!
// Render imgui, swap buffers
// (You want to try calling EndFrame/Render as late as you can, to be able to use imgui in your own game rendering code)
ImGui::EndFrame();
ImGui::Render();
ImDrawData* draw_data = ImGui::GetDrawData();
MyImGuiRenderFunction(draw_data);
SwapBuffers();
}
// Shutdown
ImGui::DestroyContext();
HOW A SIMPLE RENDERING FUNCTION MAY LOOK LIKE:
void void MyImGuiRenderFunction(ImDrawData* draw_data)
{
// TODO: Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled
// TODO: Setup viewport covering draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup orthographic projection matrix cover draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize
// TODO: Setup shader: vertex { float2 pos, float2 uv, u32 color }, fragment shader sample color from 1 texture, multiply by vertex color.
for (int n = 0; n < draw_data->CmdListsCount; n++)
{
const ImDrawList* cmd_list = draw_data->CmdLists[n];
const ImDrawVert* vtx_buffer = cmd_list->VtxBuffer.Data; // vertex buffer generated by ImGui
const ImDrawIdx* idx_buffer = cmd_list->IdxBuffer.Data; // index buffer generated by ImGui
for (int cmd_i = 0; cmd_i < cmd_list->CmdBuffer.Size; cmd_i++)
{
const ImDrawCmd* pcmd = &cmd_list->CmdBuffer[cmd_i];
if (pcmd->UserCallback)
{
pcmd->UserCallback(cmd_list, pcmd);
}
else
{
// The texture for the draw call is specified by pcmd->TextureId.
// The vast majority of draw calls will use the imgui texture atlas, which value you have set yourself during initialization.
MyEngineBindTexture((MyTexture*)pcmd->TextureId);
// We are using scissoring to clip some objects. All low-level graphics API should supports it.
// - If your engine doesn't support scissoring yet, you may ignore this at first. You will get some small glitches
// (some elements visible outside their bounds) but you can fix that once everything else works!
// - Clipping coordinates are provided in imgui coordinates space (from draw_data->DisplayPos to draw_data->DisplayPos + draw_data->DisplaySize)
// In a single viewport application, draw_data->DisplayPos will always be (0,0) and draw_data->DisplaySize will always be == io.DisplaySize.
// However, in the interest of supporting multi-viewport applications in the future (see 'viewport' branch on github),
// always subtract draw_data->DisplayPos from clipping bounds to convert them to your viewport space.
// - Note that pcmd->ClipRect contains Min+Max bounds. Some graphics API may use Min+Max, other may use Min+Size (size being Max-Min)
ImVec2 pos = draw_data->DisplayPos;
MyEngineScissor((int)(pcmd->ClipRect.x - pos.x), (int)(pcmd->ClipRect.y - pos.y), (int)(pcmd->ClipRect.z - pos.x), (int)(pcmd->ClipRect.w - pos.y));
// Render 'pcmd->ElemCount/3' indexed triangles.
// By default the indices ImDrawIdx are 16-bits, you can change them to 32-bits in imconfig.h if your engine doesn't support 16-bits indices.
MyEngineDrawIndexedTriangles(pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer, vtx_buffer);
}
idx_buffer += pcmd->ElemCount;
}
}
}
- The examples/ folders contains many actual implementation of the pseudo-codes above.
- When calling NewFrame(), the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags are updated.
They tell you if Dear ImGui intends to use your inputs. When a flag is set you want to hide the corresponding inputs
from the rest of your application. In every cases you need to pass on the inputs to imgui. Refer to the FAQ for more information.
- Please read the FAQ below!. Amusingly, it is called a FAQ because people frequently run into the same issues!
USING GAMEPAD/KEYBOARD NAVIGATION CONTROLS
- The gamepad/keyboard navigation is fairly functional and keeps being improved.
- Gamepad support is particularly useful to use dear imgui on a console system (e.g. PS4, Switch, XB1) without a mouse!
- You can ask questions and report issues at https://github.com/ocornut/imgui/issues/787
- The initial focus was to support game controllers, but keyboard is becoming increasingly and decently usable.
- Gamepad:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad to enable.
- Backend: Set io.BackendFlags |= ImGuiBackendFlags_HasGamepad + fill the io.NavInputs[] fields before calling NewFrame().
Note that io.NavInputs[] is cleared by EndFrame().
- See 'enum ImGuiNavInput_' in imgui.h for a description of inputs. For each entry of io.NavInputs[], set the following values:
0.0f= not held. 1.0f= fully held. Pass intermediate 0.0f..1.0f values for analog triggers/sticks.
- We uses a simple >0.0f test for activation testing, and won't attempt to test for a dead-zone.
Your code will probably need to transform your raw inputs (such as e.g. remapping your 0.2..0.9 raw input range to 0.0..1.0 imgui range, etc.).
- You can download PNG/PSD files depicting the gamepad controls for common controllers at: http://goo.gl/9LgVZW.
- If you need to share inputs between your game and the imgui parts, the easiest approach is to go all-or-nothing, with a buttons combo
to toggle the target. Please reach out if you think the game vs navigation input sharing could be improved.
- Keyboard:
- Set io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard to enable.
NewFrame() will automatically fill io.NavInputs[] based on your io.KeysDown[] + io.KeyMap[] arrays.
- When keyboard navigation is active (io.NavActive + ImGuiConfigFlags_NavEnableKeyboard), the io.WantCaptureKeyboard flag
will be set. For more advanced uses, you may want to read from:
- io.NavActive: true when a window is focused and it doesn't have the ImGuiWindowFlags_NoNavInputs flag set.
- io.NavVisible: true when the navigation cursor is visible (and usually goes false when mouse is used).
- or query focus information with e.g. IsWindowFocused(ImGuiFocusedFlags_AnyWindow), IsItemFocused() etc. functions.
Please reach out if you think the game vs navigation input sharing could be improved.
- Mouse:
- PS4 users: Consider emulating a mouse cursor with DualShock4 touch pad or a spare analog stick as a mouse-emulation fallback.
- Consoles/Tablet/Phone users: Consider using a Synergy 1.x server (on your PC) + uSynergy.c (on your console/tablet/phone app) to share your PC mouse/keyboard.
- On a TV/console system where readability may be lower or mouse inputs may be awkward, you may want to set the ImGuiConfigFlags_NavEnableSetMousePos flag.
Enabling ImGuiConfigFlags_NavEnableSetMousePos + ImGuiBackendFlags_HasSetMousePos instructs dear imgui to move your mouse cursor along with navigation movements.
When enabled, the NewFrame() function may alter 'io.MousePos' and set 'io.WantSetMousePos' to notify you that it wants the mouse cursor to be moved.
When that happens your back-end NEEDS to move the OS or underlying mouse cursor on the next frame. Some of the binding in examples/ do that.
(If you set the NavEnableSetMousePos flag but don't honor 'io.WantSetMousePos' properly, imgui will misbehave as it will see your mouse as moving back and forth!)
(In a setup when you may not have easy control over the mouse cursor, e.g. uSynergy.c doesn't expose moving remote mouse cursor, you may want
to set a boolean to ignore your other external mouse positions until the external source is moved again.)
API BREAKING CHANGES
====================
Occasionally introducing changes that are breaking the API. We try to make the breakage minor and easy to fix.
Below is a change-log of API breaking changes only. If you are using one of the functions listed, expect to have to fix some code.
When you are not sure about a old symbol or function name, try using the Search/Find function of your IDE to look for comments or references in all imgui files.
You can read releases logs https://github.com/ocornut/imgui/releases for more details.
(Viewport Branch)
- 2018/XX/XX (1.XX) - when multi-viewports are enabled, all positions will be in your natural OS coordinates space. It means that:
- reference to hard-coded positions such as in SetNextWindowPos(ImVec2(0,0)) are probably not what you want anymore.
you may use GetMainViewport()->Pos to offset hard-coded positions, e.g. SetNextWindowPos(GetMainViewport()->Pos)
- likewise io.MousePos and GetMousePos() will use OS coordinates.
If you query mouse positions to interact with non-imgui coordinates you will need to offset them, e.g. subtract GetWindowViewport()->Pos.
- 2018/XX/XX (1.XX) - Moved IME support functions from io.ImeSetInputScreenPosFn, io.ImeWindowHandle to the PlatformIO api.
- 2019/02/14 (1.68) - made it illegal/assert when io.DisplayTime == 0.0f (with an exception for the first frame). If for some reason your time step calculation gives you a zero value, replace it with a dummy small value!
- 2019/02/01 (1.68) - removed io.DisplayVisibleMin/DisplayVisibleMax (which were marked obsolete and removed from viewport/docking branch already).
- 2019/01/06 (1.67) - renamed io.InputCharacters[], marked internal as was always intended. Please don't access directly, and use AddInputCharacter() instead!
- 2019/01/06 (1.67) - renamed ImFontAtlas::GlyphRangesBuilder to ImFontGlyphRangesBuilder. Keep redirection typedef (will obsolete).
- 2018/12/20 (1.67) - made it illegal to call Begin("") with an empty string. This somehow half-worked before but had various undesirable side-effects.
- 2018/12/10 (1.67) - renamed io.ConfigResizeWindowsFromEdges to io.ConfigWindowsResizeFromEdges as we are doing a large pass on configuration flags.
- 2018/10/12 (1.66) - renamed misc/stl/imgui_stl.* to misc/cpp/imgui_stdlib.* in prevision for other C++ helper files.
- 2018/09/28 (1.66) - renamed SetScrollHere() to SetScrollHereY(). Kept redirection function (will obsolete).
- 2018/09/06 (1.65) - renamed stb_truetype.h to imstb_truetype.h, stb_textedit.h to imstb_textedit.h, and stb_rect_pack.h to imstb_rectpack.h.
If you were conveniently using the imgui copy of those STB headers in your project you will have to update your include paths.
- 2018/09/05 (1.65) - renamed io.OptCursorBlink/io.ConfigCursorBlink to io.ConfigInputTextCursorBlink. (#1427)
- 2018/08/31 (1.64) - added imgui_widgets.cpp file, extracted and moved widgets code out of imgui.cpp into imgui_widgets.cpp. Re-ordered some of the code remaining in imgui.cpp.
NONE OF THE FUNCTIONS HAVE CHANGED. THE CODE IS SEMANTICALLY 100% IDENTICAL, BUT _EVERY_ FUNCTION HAS BEEN MOVED.
Because of this, any local modifications to imgui.cpp will likely conflict when you update. Read docs/CHANGELOG.txt for suggestions.
- 2018/08/22 (1.63) - renamed IsItemDeactivatedAfterChange() to IsItemDeactivatedAfterEdit() for consistency with new IsItemEdited() API. Kept redirection function (will obsolete soonish as IsItemDeactivatedAfterChange() is very recent).
- 2018/08/21 (1.63) - renamed ImGuiTextEditCallback to ImGuiInputTextCallback, ImGuiTextEditCallbackData to ImGuiInputTextCallbackData for consistency. Kept redirection types (will obsolete).
- 2018/08/21 (1.63) - removed ImGuiInputTextCallbackData::ReadOnly since it is a duplication of (ImGuiInputTextCallbackData::Flags & ImGuiInputTextFlags_ReadOnly).
- 2018/08/01 (1.63) - removed per-window ImGuiWindowFlags_ResizeFromAnySide beta flag in favor of a global io.ConfigResizeWindowsFromEdges [update 1.67 renamed to ConfigWindowsResizeFromEdges] to enable the feature.
- 2018/08/01 (1.63) - renamed io.OptCursorBlink to io.ConfigCursorBlink [-> io.ConfigInputTextCursorBlink in 1.65], io.OptMacOSXBehaviors to ConfigMacOSXBehaviors for consistency.
- 2018/07/22 (1.63) - changed ImGui::GetTime() return value from float to double to avoid accumulating floating point imprecisions over time.
- 2018/07/08 (1.63) - style: renamed ImGuiCol_ModalWindowDarkening to ImGuiCol_ModalWindowDimBg for consistency with other features. Kept redirection enum (will obsolete).
- 2018/06/08 (1.62) - examples: the imgui_impl_xxx files have been split to separate platform (Win32, Glfw, SDL2, etc.) from renderer (DX11, OpenGL, Vulkan, etc.).
old binding will still work as is, however prefer using the separated bindings as they will be updated to be multi-viewport conformant.
when adopting new bindings follow the main.cpp code of your preferred examples/ folder to know which functions to call.
- 2018/06/06 (1.62) - renamed GetGlyphRangesChinese() to GetGlyphRangesChineseFull() to distinguish other variants and discourage using the full set.
- 2018/06/06 (1.62) - TreeNodeEx()/TreeNodeBehavior(): the ImGuiTreeNodeFlags_CollapsingHeader helper now include the ImGuiTreeNodeFlags_NoTreePushOnOpen flag. See Changelog for details.
- 2018/05/03 (1.61) - DragInt(): the default compile-time format string has been changed from "%.0f" to "%d", as we are not using integers internally any more.
If you used DragInt() with custom format strings, make sure you change them to use %d or an integer-compatible format.
To honor backward-compatibility, the DragInt() code will currently parse and modify format strings to replace %*f with %d, giving time to users to upgrade their code.
If you have IMGUI_DISABLE_OBSOLETE_FUNCTIONS enabled, the code will instead assert! You may run a reg-exp search on your codebase for e.g. "DragInt.*%f" to help you find them.
- 2018/04/28 (1.61) - obsoleted InputFloat() functions taking an optional "int decimal_precision" in favor of an equivalent and more flexible "const char* format",
consistent with other functions. Kept redirection functions (will obsolete).
- 2018/04/09 (1.61) - IM_DELETE() helper function added in 1.60 doesn't clear the input _pointer_ reference, more consistent with expectation and allows passing r-value.
- 2018/03/20 (1.60) - renamed io.WantMoveMouse to io.WantSetMousePos for consistency and ease of understanding (was added in 1.52, _not_ used by core and only honored by some binding ahead of merging the Nav branch).
- 2018/03/12 (1.60) - removed ImGuiCol_CloseButton, ImGuiCol_CloseButtonActive, ImGuiCol_CloseButtonHovered as the closing cross uses regular button colors now.
- 2018/03/08 (1.60) - changed ImFont::DisplayOffset.y to default to 0 instead of +1. Fixed rounding of Ascent/Descent to match TrueType renderer. If you were adding or subtracting to ImFont::DisplayOffset check if your fonts are correctly aligned vertically.
- 2018/03/03 (1.60) - renamed ImGuiStyleVar_Count_ to ImGuiStyleVar_COUNT and ImGuiMouseCursor_Count_ to ImGuiMouseCursor_COUNT for consistency with other public enums.
- 2018/02/18 (1.60) - BeginDragDropSource(): temporarily removed the optional mouse_button=0 parameter because it is not really usable in many situations at the moment.
- 2018/02/16 (1.60) - obsoleted the io.RenderDrawListsFn callback, you can call your graphics engine render function after ImGui::Render(). Use ImGui::GetDrawData() to retrieve the ImDrawData* to display.
- 2018/02/07 (1.60) - reorganized context handling to be more explicit,
- YOU NOW NEED TO CALL ImGui::CreateContext() AT THE BEGINNING OF YOUR APP, AND CALL ImGui::DestroyContext() AT THE END.
- removed Shutdown() function, as DestroyContext() serve this purpose.
- you may pass a ImFontAtlas* pointer to CreateContext() to share a font atlas between contexts. Otherwise CreateContext() will create its own font atlas instance.
- removed allocator parameters from CreateContext(), they are now setup with SetAllocatorFunctions(), and shared by all contexts.
- removed the default global context and font atlas instance, which were confusing for users of DLL reloading and users of multiple contexts.
- 2018/01/31 (1.60) - moved sample TTF files from extra_fonts/ to misc/fonts/. If you loaded files directly from the imgui repo you may need to update your paths.
- 2018/01/11 (1.60) - obsoleted IsAnyWindowHovered() in favor of IsWindowHovered(ImGuiHoveredFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/11 (1.60) - obsoleted IsAnyWindowFocused() in favor of IsWindowFocused(ImGuiFocusedFlags_AnyWindow). Kept redirection function (will obsolete).
- 2018/01/03 (1.60) - renamed ImGuiSizeConstraintCallback to ImGuiSizeCallback, ImGuiSizeConstraintCallbackData to ImGuiSizeCallbackData.
- 2017/12/29 (1.60) - removed CalcItemRectClosestPoint() which was weird and not really used by anyone except demo code. If you need it it's easy to replicate on your side.
- 2017/12/24 (1.53) - renamed the emblematic ShowTestWindow() function to ShowDemoWindow(). Kept redirection function (will obsolete).
- 2017/12/21 (1.53) - ImDrawList: renamed style.AntiAliasedShapes to style.AntiAliasedFill for consistency and as a way to explicitly break code that manipulate those flag at runtime. You can now manipulate ImDrawList::Flags
- 2017/12/21 (1.53) - ImDrawList: removed 'bool anti_aliased = true' final parameter of ImDrawList::AddPolyline() and ImDrawList::AddConvexPolyFilled(). Prefer manipulating ImDrawList::Flags if you need to toggle them during the frame.
- 2017/12/14 (1.53) - using the ImGuiWindowFlags_NoScrollWithMouse flag on a child window forwards the mouse wheel event to the parent window, unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set.
- 2017/12/13 (1.53) - renamed GetItemsLineHeightWithSpacing() to GetFrameHeightWithSpacing(). Kept redirection function (will obsolete).
- 2017/12/13 (1.53) - obsoleted IsRootWindowFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootWindow). Kept redirection function (will obsolete).
- obsoleted IsRootWindowOrAnyChildFocused() in favor of using IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows). Kept redirection function (will obsolete).
- 2017/12/12 (1.53) - renamed ImGuiTreeNodeFlags_AllowOverlapMode to ImGuiTreeNodeFlags_AllowItemOverlap. Kept redirection enum (will obsolete).
- 2017/12/10 (1.53) - removed SetNextWindowContentWidth(), prefer using SetNextWindowContentSize(). Kept redirection function (will obsolete).
- 2017/11/27 (1.53) - renamed ImGuiTextBuffer::append() helper to appendf(), appendv() to appendfv(). If you copied the 'Log' demo in your code, it uses appendv() so that needs to be renamed.
- 2017/11/18 (1.53) - Style, Begin: removed ImGuiWindowFlags_ShowBorders window flag. Borders are now fully set up in the ImGuiStyle structure (see e.g. style.FrameBorderSize, style.WindowBorderSize). Use ImGui::ShowStyleEditor() to look them up.
Please note that the style system will keep evolving (hopefully stabilizing in Q1 2018), and so custom styles will probably subtly break over time. It is recommended you use the StyleColorsClassic(), StyleColorsDark(), StyleColorsLight() functions.
- 2017/11/18 (1.53) - Style: removed ImGuiCol_ComboBg in favor of combo boxes using ImGuiCol_PopupBg for consistency.
- 2017/11/18 (1.53) - Style: renamed ImGuiCol_ChildWindowBg to ImGuiCol_ChildBg.
- 2017/11/18 (1.53) - Style: renamed style.ChildWindowRounding to style.ChildRounding, ImGuiStyleVar_ChildWindowRounding to ImGuiStyleVar_ChildRounding.
- 2017/11/02 (1.53) - obsoleted IsRootWindowOrAnyChildHovered() in favor of using IsWindowHovered(ImGuiHoveredFlags_RootAndChildWindows);
- 2017/10/24 (1.52) - renamed IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCS to IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS/IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS for consistency.
- 2017/10/20 (1.52) - changed IsWindowHovered() default parameters behavior to return false if an item is active in another window (e.g. click-dragging item from another window to this window). You can use the newly introduced IsWindowHovered() flags to requests this specific behavior if you need it.
- 2017/10/20 (1.52) - marked IsItemHoveredRect()/IsMouseHoveringWindow() as obsolete, in favor of using the newly introduced flags for IsItemHovered() and IsWindowHovered(). See https://github.com/ocornut/imgui/issues/1382 for details.
removed the IsItemRectHovered()/IsWindowRectHovered() names introduced in 1.51 since they were merely more consistent names for the two functions we are now obsoleting.
- 2017/10/17 (1.52) - marked the old 5-parameters version of Begin() as obsolete (still available). Use SetNextWindowSize()+Begin() instead!
- 2017/10/11 (1.52) - renamed AlignFirstTextHeightToWidgets() to AlignTextToFramePadding(). Kept inline redirection function (will obsolete).
- 2017/09/26 (1.52) - renamed ImFont::Glyph to ImFontGlyph. Keep redirection typedef (will obsolete).
- 2017/09/25 (1.52) - removed SetNextWindowPosCenter() because SetNextWindowPos() now has the optional pivot information to do the same and more. Kept redirection function (will obsolete).
- 2017/08/25 (1.52) - io.MousePos needs to be set to ImVec2(-FLT_MAX,-FLT_MAX) when mouse is unavailable/missing. Previously ImVec2(-1,-1) was enough but we now accept negative mouse coordinates. In your binding if you need to support unavailable mouse, make sure to replace "io.MousePos = ImVec2(-1,-1)" with "io.MousePos = ImVec2(-FLT_MAX,-FLT_MAX)".
- 2017/08/22 (1.51) - renamed IsItemHoveredRect() to IsItemRectHovered(). Kept inline redirection function (will obsolete). -> (1.52) use IsItemHovered(ImGuiHoveredFlags_RectOnly)!
- renamed IsMouseHoveringAnyWindow() to IsAnyWindowHovered() for consistency. Kept inline redirection function (will obsolete).
- renamed IsMouseHoveringWindow() to IsWindowRectHovered() for consistency. Kept inline redirection function (will obsolete).
- 2017/08/20 (1.51) - renamed GetStyleColName() to GetStyleColorName() for consistency.
- 2017/08/20 (1.51) - added PushStyleColor(ImGuiCol idx, ImU32 col) overload, which _might_ cause an "ambiguous call" compilation error if you are using ImColor() with implicit cast. Cast to ImU32 or ImVec4 explicily to fix.
- 2017/08/15 (1.51) - marked the weird IMGUI_ONCE_UPON_A_FRAME helper macro as obsolete. prefer using the more explicit ImGuiOnceUponAFrame.
- 2017/08/15 (1.51) - changed parameter order for BeginPopupContextWindow() from (const char*,int buttons,bool also_over_items) to (const char*,int buttons,bool also_over_items). Note that most calls relied on default parameters completely.
- 2017/08/13 (1.51) - renamed ImGuiCol_Columns*** to ImGuiCol_Separator***. Kept redirection enums (will obsolete).
- 2017/08/11 (1.51) - renamed ImGuiSetCond_*** types and flags to ImGuiCond_***. Kept redirection enums (will obsolete).
- 2017/08/09 (1.51) - removed ValueColor() helpers, they are equivalent to calling Text(label) + SameLine() + ColorButton().
- 2017/08/08 (1.51) - removed ColorEditMode() and ImGuiColorEditMode in favor of ImGuiColorEditFlags and parameters to the various Color*() functions. The SetColorEditOptions() allows to initialize default but the user can still change them with right-click context menu.
- changed prototype of 'ColorEdit4(const char* label, float col[4], bool show_alpha = true)' to 'ColorEdit4(const char* label, float col[4], ImGuiColorEditFlags flags = 0)', where passing flags = 0x01 is a safe no-op (hello dodgy backward compatibility!). - check and run the demo window, under "Color/Picker Widgets", to understand the various new options.
- changed prototype of rarely used 'ColorButton(ImVec4 col, bool small_height = false, bool outline_border = true)' to 'ColorButton(const char* desc_id, ImVec4 col, ImGuiColorEditFlags flags = 0, ImVec2 size = ImVec2(0,0))'
- 2017/07/20 (1.51) - removed IsPosHoveringAnyWindow(ImVec2), which was partly broken and misleading. ASSERT + redirect user to io.WantCaptureMouse
- 2017/05/26 (1.50) - removed ImFontConfig::MergeGlyphCenterV in favor of a more multipurpose ImFontConfig::GlyphOffset.
- 2017/05/01 (1.50) - renamed ImDrawList::PathFill() (rarely used directly) to ImDrawList::PathFillConvex() for clarity.
- 2016/11/06 (1.50) - BeginChild(const char*) now applies the stack id to the provided label, consistently with other functions as it should always have been. It shouldn't affect you unless (extremely unlikely) you were appending multiple times to a same child from different locations of the stack id. If that's the case, generate an id with GetId() and use it instead of passing string to BeginChild().
- 2016/10/15 (1.50) - avoid 'void* user_data' parameter to io.SetClipboardTextFn/io.GetClipboardTextFn pointers. We pass io.ClipboardUserData to it.
- 2016/09/25 (1.50) - style.WindowTitleAlign is now a ImVec2 (ImGuiAlign enum was removed). set to (0.5f,0.5f) for horizontal+vertical centering, (0.0f,0.0f) for upper-left, etc.
- 2016/07/30 (1.50) - SameLine(x) with x>0.0f is now relative to left of column/group if any, and not always to left of window. This was sort of always the intent and hopefully breakage should be minimal.
- 2016/05/12 (1.49) - title bar (using ImGuiCol_TitleBg/ImGuiCol_TitleBgActive colors) isn't rendered over a window background (ImGuiCol_WindowBg color) anymore.
If your TitleBg/TitleBgActive alpha was 1.0f or you are using the default theme it will not affect you.
If your TitleBg/TitleBgActive alpha was <1.0f you need to tweak your custom theme to readjust for the fact that we don't draw a WindowBg background behind the title bar.
This helper function will convert an old TitleBg/TitleBgActive color into a new one with the same visual output, given the OLD color and the OLD WindowBg color.
ImVec4 ConvertTitleBgCol(const ImVec4& win_bg_col, const ImVec4& title_bg_col)
{
float new_a = 1.0f - ((1.0f - win_bg_col.w) * (1.0f - title_bg_col.w)), k = title_bg_col.w / new_a;
return ImVec4((win_bg_col.x * win_bg_col.w + title_bg_col.x) * k, (win_bg_col.y * win_bg_col.w + title_bg_col.y) * k, (win_bg_col.z * win_bg_col.w + title_bg_col.z) * k, new_a);
}
If this is confusing, pick the RGB value from title bar from an old screenshot and apply this as TitleBg/TitleBgActive. Or you may just create TitleBgActive from a tweaked TitleBg color.
- 2016/05/07 (1.49) - removed confusing set of GetInternalState(), GetInternalStateSize(), SetInternalState() functions. Now using CreateContext(), DestroyContext(), GetCurrentContext(), SetCurrentContext().
- 2016/05/02 (1.49) - renamed SetNextTreeNodeOpened() to SetNextTreeNodeOpen(), no redirection.
- 2016/05/01 (1.49) - obsoleted old signature of CollapsingHeader(const char* label, const char* str_id = NULL, bool display_frame = true, bool default_open = false) as extra parameters were badly designed and rarely used. You can replace the "default_open = true" flag in new API with CollapsingHeader(label, ImGuiTreeNodeFlags_DefaultOpen).
- 2016/04/26 (1.49) - changed ImDrawList::PushClipRect(ImVec4 rect) to ImDrawList::PushClipRect(Imvec2 min,ImVec2 max,bool intersect_with_current_clip_rect=false). Note that higher-level ImGui::PushClipRect() is preferable because it will clip at logic/widget level, whereas ImDrawList::PushClipRect() only affect your renderer.
- 2016/04/03 (1.48) - removed style.WindowFillAlphaDefault setting which was redundant. Bake default BG alpha inside style.Colors[ImGuiCol_WindowBg] and all other Bg color values. (ref github issue #337).
- 2016/04/03 (1.48) - renamed ImGuiCol_TooltipBg to ImGuiCol_PopupBg, used by popups/menus and tooltips. popups/menus were previously using ImGuiCol_WindowBg. (ref github issue #337)
- 2016/03/21 (1.48) - renamed GetWindowFont() to GetFont(), GetWindowFontSize() to GetFontSize(). Kept inline redirection function (will obsolete).
- 2016/03/02 (1.48) - InputText() completion/history/always callbacks: if you modify the text buffer manually (without using DeleteChars()/InsertChars() helper) you need to maintain the BufTextLen field. added an assert.
- 2016/01/23 (1.48) - fixed not honoring exact width passed to PushItemWidth(), previously it would add extra FramePadding.x*2 over that width. if you had manual pixel-perfect alignment in place it might affect you.
- 2015/12/27 (1.48) - fixed ImDrawList::AddRect() which used to render a rectangle 1 px too large on each axis.
- 2015/12/04 (1.47) - renamed Color() helpers to ValueColor() - dangerously named, rarely used and probably to be made obsolete.
- 2015/08/29 (1.45) - with the addition of horizontal scrollbar we made various fixes to inconsistencies with dealing with cursor position.
GetCursorPos()/SetCursorPos() functions now include the scrolled amount. It shouldn't affect the majority of users, but take note that SetCursorPosX(100.0f) puts you at +100 from the starting x position which may include scrolling, not at +100 from the window left side.
GetContentRegionMax()/GetWindowContentRegionMin()/GetWindowContentRegionMax() functions allow include the scrolled amount. Typically those were used in cases where no scrolling would happen so it may not be a problem, but watch out!
- 2015/08/29 (1.45) - renamed style.ScrollbarWidth to style.ScrollbarSize
- 2015/08/05 (1.44) - split imgui.cpp into extra files: imgui_demo.cpp imgui_draw.cpp imgui_internal.h that you need to add to your project.
- 2015/07/18 (1.44) - fixed angles in ImDrawList::PathArcTo(), PathArcToFast() (introduced in 1.43) being off by an extra PI for no justifiable reason
- 2015/07/14 (1.43) - add new ImFontAtlas::AddFont() API. For the old AddFont***, moved the 'font_no' parameter of ImFontAtlas::AddFont** functions to the ImFontConfig structure.
you need to render your textured triangles with bilinear filtering to benefit from sub-pixel positioning of text.
- 2015/07/08 (1.43) - switched rendering data to use indexed rendering. this is saving a fair amount of CPU/GPU and enables us to get anti-aliasing for a marginal cost.
this necessary change will break your rendering function! the fix should be very easy. sorry for that :(
- if you are using a vanilla copy of one of the imgui_impl_XXXX.cpp provided in the example, you just need to update your copy and you can ignore the rest.
- the signature of the io.RenderDrawListsFn handler has changed!
old: ImGui_XXXX_RenderDrawLists(ImDrawList** const cmd_lists, int cmd_lists_count)
new: ImGui_XXXX_RenderDrawLists(ImDrawData* draw_data).
parameters: 'cmd_lists' becomes 'draw_data->CmdLists', 'cmd_lists_count' becomes 'draw_data->CmdListsCount'
ImDrawList: 'commands' becomes 'CmdBuffer', 'vtx_buffer' becomes 'VtxBuffer', 'IdxBuffer' is new.
ImDrawCmd: 'vtx_count' becomes 'ElemCount', 'clip_rect' becomes 'ClipRect', 'user_callback' becomes 'UserCallback', 'texture_id' becomes 'TextureId'.
- each ImDrawList now contains both a vertex buffer and an index buffer. For each command, render ElemCount/3 triangles using indices from the index buffer.
- if you REALLY cannot render indexed primitives, you can call the draw_data->DeIndexAllBuffers() method to de-index the buffers. This is slow and a waste of CPU/GPU. Prefer using indexed rendering!
- refer to code in the examples/ folder or ask on the GitHub if you are unsure of how to upgrade. please upgrade!
- 2015/07/10 (1.43) - changed SameLine() parameters from int to float.
- 2015/07/02 (1.42) - renamed SetScrollPosHere() to SetScrollFromCursorPos(). Kept inline redirection function (will obsolete).
- 2015/07/02 (1.42) - renamed GetScrollPosY() to GetScrollY(). Necessary to reduce confusion along with other scrolling functions, because positions (e.g. cursor position) are not equivalent to scrolling amount.
- 2015/06/14 (1.41) - changed ImageButton() default bg_col parameter from (0,0,0,1) (black) to (0,0,0,0) (transparent) - makes a difference when texture have transparence
- 2015/06/14 (1.41) - changed Selectable() API from (label, selected, size) to (label, selected, flags, size). Size override should have been rarely be used. Sorry!
- 2015/05/31 (1.40) - renamed GetWindowCollapsed() to IsWindowCollapsed() for consistency. Kept inline redirection function (will obsolete).
- 2015/05/31 (1.40) - renamed IsRectClipped() to IsRectVisible() for consistency. Note that return value is opposite! Kept inline redirection function (will obsolete).
- 2015/05/27 (1.40) - removed the third 'repeat_if_held' parameter from Button() - sorry! it was rarely used and inconsistent. Use PushButtonRepeat(true) / PopButtonRepeat() to enable repeat on desired buttons.
- 2015/05/11 (1.40) - changed BeginPopup() API, takes a string identifier instead of a bool. ImGui needs to manage the open/closed state of popups. Call OpenPopup() to actually set the "open" state of a popup. BeginPopup() returns true if the popup is opened.
- 2015/05/03 (1.40) - removed style.AutoFitPadding, using style.WindowPadding makes more sense (the default values were already the same).
- 2015/04/13 (1.38) - renamed IsClipped() to IsRectClipped(). Kept inline redirection function until 1.50.
- 2015/04/09 (1.38) - renamed ImDrawList::AddArc() to ImDrawList::AddArcFast() for compatibility with future API
- 2015/04/03 (1.38) - removed ImGuiCol_CheckHovered, ImGuiCol_CheckActive, replaced with the more general ImGuiCol_FrameBgHovered, ImGuiCol_FrameBgActive.
- 2014/04/03 (1.38) - removed support for passing -FLT_MAX..+FLT_MAX as the range for a SliderFloat(). Use DragFloat() or Inputfloat() instead.
- 2015/03/17 (1.36) - renamed GetItemBoxMin()/GetItemBoxMax()/IsMouseHoveringBox() to GetItemRectMin()/GetItemRectMax()/IsMouseHoveringRect(). Kept inline redirection function until 1.50.
- 2015/03/15 (1.36) - renamed style.TreeNodeSpacing to style.IndentSpacing, ImGuiStyleVar_TreeNodeSpacing to ImGuiStyleVar_IndentSpacing
- 2015/03/13 (1.36) - renamed GetWindowIsFocused() to IsWindowFocused(). Kept inline redirection function until 1.50.
- 2015/03/08 (1.35) - renamed style.ScrollBarWidth to style.ScrollbarWidth (casing)
- 2015/02/27 (1.34) - renamed OpenNextNode(bool) to SetNextTreeNodeOpened(bool, ImGuiSetCond). Kept inline redirection function until 1.50.
- 2015/02/27 (1.34) - renamed ImGuiSetCondition_*** to ImGuiSetCond_***, and _FirstUseThisSession becomes _Once.
- 2015/02/11 (1.32) - changed text input callback ImGuiTextEditCallback return type from void-->int. reserved for future use, return 0 for now.
- 2015/02/10 (1.32) - renamed GetItemWidth() to CalcItemWidth() to clarify its evolving behavior
- 2015/02/08 (1.31) - renamed GetTextLineSpacing() to GetTextLineHeightWithSpacing()
- 2015/02/01 (1.31) - removed IO.MemReallocFn (unused)
- 2015/01/19 (1.30) - renamed ImGuiStorage::GetIntPtr()/GetFloatPtr() to GetIntRef()/GetIntRef() because Ptr was conflicting with actual pointer storage functions.
- 2015/01/11 (1.30) - big font/image API change! now loads TTF file. allow for multiple fonts. no need for a PNG loader.
(1.30) - removed GetDefaultFontData(). uses io.Fonts->GetTextureData*() API to retrieve uncompressed pixels.
font init: { const void* png_data; unsigned int png_size; ImGui::GetDefaultFontData(NULL, NULL, &png_data, &png_size); <..Upload texture to GPU..>; }
became: { unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); <..Upload texture to GPU>; io.Fonts->TexId = YourTextureIdentifier; }
you now have more flexibility to load multiple TTF fonts and manage the texture buffer for internal needs.
it is now recommended that you sample the font texture with bilinear interpolation.
(1.30) - added texture identifier in ImDrawCmd passed to your render function (we can now render images). make sure to set io.Fonts->TexID.
(1.30) - removed IO.PixelCenterOffset (unnecessary, can be handled in user projection matrix)
(1.30) - removed ImGui::IsItemFocused() in favor of ImGui::IsItemActive() which handles all widgets
- 2014/12/10 (1.18) - removed SetNewWindowDefaultPos() in favor of new generic API SetNextWindowPos(pos, ImGuiSetCondition_FirstUseEver)
- 2014/11/28 (1.17) - moved IO.Font*** options to inside the IO.Font-> structure (FontYOffset, FontTexUvForWhite, FontBaseScale, FontFallbackGlyph)
- 2014/11/26 (1.17) - reworked syntax of IMGUI_ONCE_UPON_A_FRAME helper macro to increase compiler compatibility
- 2014/11/07 (1.15) - renamed IsHovered() to IsItemHovered()
- 2014/10/02 (1.14) - renamed IMGUI_INCLUDE_IMGUI_USER_CPP to IMGUI_INCLUDE_IMGUI_USER_INL and imgui_user.cpp to imgui_user.inl (more IDE friendly)
- 2014/09/25 (1.13) - removed 'text_end' parameter from IO.SetClipboardTextFn (the string is now always zero-terminated for simplicity)
- 2014/09/24 (1.12) - renamed SetFontScale() to SetWindowFontScale()
- 2014/09/24 (1.12) - moved IM_MALLOC/IM_REALLOC/IM_FREE preprocessor defines to IO.MemAllocFn/IO.MemReallocFn/IO.MemFreeFn
- 2014/08/30 (1.09) - removed IO.FontHeight (now computed automatically)
- 2014/08/30 (1.09) - moved IMGUI_FONT_TEX_UV_FOR_WHITE preprocessor define to IO.FontTexUvForWhite
- 2014/08/28 (1.09) - changed the behavior of IO.PixelCenterOffset following various rendering fixes
FREQUENTLY ASKED QUESTIONS (FAQ), TIPS
======================================
Q: How can I tell whether to dispatch mouse/keyboard to imgui or to my application?
A: You can read the 'io.WantCaptureMouse', 'io.WantCaptureKeyboard' and 'io.WantTextInput' flags from the ImGuiIO structure (e.g. if (ImGui::GetIO().WantCaptureMouse) { ... } )
- When 'io.WantCaptureMouse' is set, imgui wants to use your mouse state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantCaptureKeyboard' is set, imgui wants to use your keyboard state, and you may want to discard/hide the inputs from the rest of your application.
- When 'io.WantTextInput' is set to may want to notify your OS to popup an on-screen keyboard, if available (e.g. on a mobile phone, or console OS).
Note: you should always pass your mouse/keyboard inputs to imgui, even when the io.WantCaptureXXX flag are set false.
This is because imgui needs to detect that you clicked in the void to unfocus its own windows.
Note: The 'io.WantCaptureMouse' is more accurate that any attempt to "check if the mouse is hovering a window" (don't do that!).
It handle mouse dragging correctly (both dragging that started over your application or over an imgui window) and handle e.g. modal windows blocking inputs.
Those flags are updated by ImGui::NewFrame(). Preferably read the flags after calling NewFrame() if you can afford it, but reading them before is also
perfectly fine, as the bool toggle fairly rarely. If you have on a touch device, you might find use for an early call to UpdateHoveredWindowAndCaptureFlags().
Note: Text input widget releases focus on "Return KeyDown", so the subsequent "Return KeyUp" event that your application receive will typically
have 'io.WantCaptureKeyboard=false'. Depending on your application logic it may or not be inconvenient. You might want to track which key-downs
were targeted for Dear ImGui, e.g. with an array of bool, and filter out the corresponding key-ups.)
Q: How can I display an image? What is ImTextureID, how does it works?
A: Short explanation:
- You may use functions such as ImGui::Image(), ImGui::ImageButton() or lower-level ImDrawList::AddImage() to emit draw calls that will use your own textures.
- Actual textures are identified in a way that is up to the user/engine. Those identifiers are stored and passed as ImTextureID (void*) value.
- Loading image files from the disk and turning them into a texture is not within the scope of Dear ImGui (for a good reason).
Please read documentations or tutorials on your graphics API to understand how to display textures on the screen before moving onward.
Long explanation:
- Dear ImGui's job is to create "meshes", defined in a renderer-agnostic format made of draw commands and vertices.
At the end of the frame those meshes (ImDrawList) will be displayed by your rendering function. They are made up of textured polygons and the code
to render them is generally fairly short (a few dozen lines). In the examples/ folder we provide functions for popular graphics API (OpenGL, DirectX, etc.).
- Each rendering function decides on a data type to represent "textures". The concept of what is a "texture" is entirely tied to your underlying engine/graphics API.
We carry the information to identify a "texture" in the ImTextureID type.
ImTextureID is nothing more that a void*, aka 4/8 bytes worth of data: just enough to store 1 pointer or 1 integer of your choice.
Dear ImGui doesn't know or understand what you are storing in ImTextureID, it merely pass ImTextureID values until they reach your rendering function.
- In the examples/ bindings, for each graphics API binding we decided on a type that is likely to be a good representation for specifying
an image from the end-user perspective. This is what the _examples_ rendering functions are using:
OpenGL: ImTextureID = GLuint (see ImGui_ImplGlfwGL3_RenderDrawData() function in imgui_impl_glfw_gl3.cpp)
DirectX9: ImTextureID = LPDIRECT3DTEXTURE9 (see ImGui_ImplDX9_RenderDrawData() function in imgui_impl_dx9.cpp)
DirectX11: ImTextureID = ID3D11ShaderResourceView* (see ImGui_ImplDX11_RenderDrawData() function in imgui_impl_dx11.cpp)
DirectX12: ImTextureID = D3D12_GPU_DESCRIPTOR_HANDLE (see ImGui_ImplDX12_RenderDrawData() function in imgui_impl_dx12.cpp)
For example, in the OpenGL example binding we store raw OpenGL texture identifier (GLuint) inside ImTextureID.
Whereas in the DirectX11 example binding we store a pointer to ID3D11ShaderResourceView inside ImTextureID, which is a higher-level structure
tying together both the texture and information about its format and how to read it.
- If you have a custom engine built over e.g. OpenGL, instead of passing GLuint around you may decide to use a high-level data type to carry information about
the texture as well as how to display it (shaders, etc.). The decision of what to use as ImTextureID can always be made better knowing how your codebase
is designed. If your engine has high-level data types for "textures" and "material" then you may want to use them.
If you are starting with OpenGL or DirectX or Vulkan and haven't built much of a rendering engine over them, keeping the default ImTextureID
representation suggested by the example bindings is probably the best choice.
(Advanced users may also decide to keep a low-level type in ImTextureID, and use ImDrawList callback and pass information to their renderer)
User code may do:
// Cast our texture type to ImTextureID / void*
MyTexture* texture = g_CoffeeTableTexture;
ImGui::Image((void*)texture, ImVec2(texture->Width, texture->Height));
The renderer function called after ImGui::Render() will receive that same value that the user code passed:
// Cast ImTextureID / void* stored in the draw command as our texture type
MyTexture* texture = (MyTexture*)pcmd->TextureId;
MyEngineBindTexture2D(texture);
Once you understand this design you will understand that loading image files and turning them into displayable textures is not within the scope of Dear ImGui.
This is by design and is actually a good thing, because it means your code has full control over your data types and how you display them.
If you want to display an image file (e.g. PNG file) into the screen, please refer to documentation and tutorials for the graphics API you are using.
Here's a simplified OpenGL example using stb_image.h:
// Use stb_image.h to load a PNG from disk and turn it into raw RGBA pixel data:
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
[...]
int my_image_width, my_image_height;
unsigned char* my_image_data = stbi_load("my_image.png", &my_image_width, &my_image_height, NULL, 4);
// Turn the RGBA pixel data into an OpenGL texture:
GLuint my_opengl_texture;
glGenTextures(1, &my_opengl_texture);
glBindTexture(GL_TEXTURE_2D, my_opengl_texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image_data);
// Now that we have an OpenGL texture, assuming our imgui rendering function (imgui_impl_xxx.cpp file) takes GLuint as ImTextureID, we can display it:
ImGui::Image((void*)(intptr_t)my_opengl_texture, ImVec2(my_image_width, my_image_height));
C/C++ tip: a void* is pointer-sized storage. You may safely store any pointer or integer into it by casting your value to ImTexture / void*, and vice-versa.
Because both end-points (user code and rendering function) are under your control, you know exactly what is stored inside the ImTexture / void*.
Examples:
GLuint my_tex = XXX;
void* my_void_ptr;
my_void_ptr = (void*)(intptr_t)my_tex; // cast a GLuint into a void* (we don't take its address! we literally store the value inside the pointer)
my_tex = (GLuint)(intptr_t)my_void_ptr; // cast a void* into a GLuint
ID3D11ShaderResourceView* my_dx11_srv = XXX;
void* my_void_ptr;
my_void_ptr = (void*)my_dx11_srv; // cast a ID3D11ShaderResourceView* into an opaque void*
my_dx11_srv = (ID3D11ShaderResourceView*)my_void_ptr; // cast a void* into a ID3D11ShaderResourceView*
Finally, you may call ImGui::ShowMetricsWindow() to explore/visualize/understand how the ImDrawList are generated.
Q: How can I have multiple widgets with the same label or with an empty label?
Q: I have multiple widgets with the same label, and only the first one works. Why is that?
A: A primer on labels and the ID Stack...
Dear ImGui internally need to uniquely identify UI elements.
Elements that are typically not clickable (such as calls to the Text functions) don't need an ID.
Interactive widgets (such as calls to Button buttons) need a unique ID.
Unique ID are used internally to track active widgets and occasionally associate state to widgets.
Unique ID are implicitly built from the hash of multiple elements that identify the "path" to the UI element.
- Unique ID are often derived from a string label:
Button("OK"); // Label = "OK", ID = hash of (..., "OK")
Button("Cancel"); // Label = "Cancel", ID = hash of (..., "Cancel")
- ID are uniquely scoped within windows, tree nodes, etc. which all pushes to the ID stack. Having
two buttons labeled "OK" in different windows or different tree locations is fine.
We used "..." above to signify whatever was already pushed to the ID stack previously:
Begin("MyWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyWindow", "OK")
End();
Begin("MyOtherWindow");
Button("OK"); // Label = "OK", ID = hash of ("MyOtherWindow", "OK")
End();
- If you have a same ID twice in the same location, you'll have a conflict:
Button("OK");
Button("OK"); // ID collision! Interacting with either button will trigger the first one.
Fear not! this is easy to solve and there are many ways to solve it!
- Solving ID conflict in a simple/local context:
When passing a label you can optionally specify extra ID information within string itself.
Use "##" to pass a complement to the ID that won't be visible to the end-user.
This helps solving the simple collision cases when you know e.g. at compilation time which items
are going to be created:
Begin("MyWindow");
Button("Play"); // Label = "Play", ID = hash of ("MyWindow", "Play")
Button("Play##foo1"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo1") // Different from above
Button("Play##foo2"); // Label = "Play", ID = hash of ("MyWindow", "Play##foo2") // Different from above
End();
- If you want to completely hide the label, but still need an ID:
Checkbox("##On", &b); // Label = "", ID = hash of (..., "##On") // No visible label, just a checkbox!
- Occasionally/rarely you might want change a label while preserving a constant ID. This allows
you to animate labels. For example you may want to include varying information in a window title bar,
but windows are uniquely identified by their ID. Use "###" to pass a label that isn't part of ID:
Button("Hello###ID"); // Label = "Hello", ID = hash of (..., "###ID")
Button("World###ID"); // Label = "World", ID = hash of (..., "###ID") // Same as above, even though the label looks different
sprintf(buf, "My game (%f FPS)###MyGame", fps);
Begin(buf); // Variable title, ID = hash of "MyGame"
- Solving ID conflict in a more general manner:
Use PushID() / PopID() to create scopes and manipulate the ID stack, as to avoid ID conflicts
within the same window. This is the most convenient way of distinguishing ID when iterating and
creating many UI elements programmatically.
You can push a pointer, a string or an integer value into the ID stack.
Remember that ID are formed from the concatenation of _everything_ pushed into the ID stack.
At each level of the stack we store the seed used for items at this level of the ID stack.
Begin("Window");
for (int i = 0; i < 100; i++)
{
PushID(i); // Push i to the id tack
Button("Click"); // Label = "Click", ID = hash of ("Window", i, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj pointer, "Click")
PopID();
}
for (int i = 0; i < 100; i++)
{
MyObject* obj = Objects[i];
PushID(obj->Name);
Button("Click"); // Label = "Click", ID = hash of ("Window", obj->Name, "Click")
PopID();
}
End();
- You can stack multiple prefixes into the ID stack:
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
PushID("node");
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
PushID(my_ptr);
Button("Click"); // Label = "Click", ID = hash of (..., "node", my_ptr, "Click")
PopID();
PopID();
- Tree nodes implicitly creates a scope for you by calling PushID().
Button("Click"); // Label = "Click", ID = hash of (..., "Click")
if (TreeNode("node")) // <-- this function call will do a PushID() for you (unless instructed not to, with a special flag)
{
Button("Click"); // Label = "Click", ID = hash of (..., "node", "Click")
TreePop();
}
- When working with trees, ID are used to preserve the open/close state of each tree node.
Depending on your use cases you may want to use strings, indices or pointers as ID.
e.g. when following a single pointer that may change over time, using a static string as ID
will preserve your node open/closed state when the targeted object change.
e.g. when displaying a list of objects, using indices or pointers as ID will preserve the
node open/closed state differently. See what makes more sense in your situation!
Q: How can I use my own math types instead of ImVec2/ImVec4?
A: You can edit imconfig.h and setup the IM_VEC2_CLASS_EXTRA/IM_VEC4_CLASS_EXTRA macros to add implicit type conversions.
This way you'll be able to use your own types everywhere, e.g. passsing glm::vec2 to ImGui functions instead of ImVec2.
Q: How can I load a different font than the default?
A: Use the font atlas to load the TTF/OTF file you want:
ImGuiIO& io = ImGui::GetIO();
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
Default is ProggyClean.ttf, monospace, rendered at size 13, embedded in dear imgui's source code.
(Tip: monospace fonts are convenient because they allow to facilitate horizontal alignment directly at the string level.)
(Read the 'misc/fonts/README.txt' file for more details about font loading.)
New programmers: remember that in C/C++ and most programming languages if you want to use a
backslash \ within a string literal, you need to write it double backslash "\\":
io.Fonts->AddFontFromFileTTF("MyDataFolder\MyFontFile.ttf", size_in_pixels); // WRONG (you are escape the M here!)
io.Fonts->AddFontFromFileTTF("MyDataFolder\\MyFontFile.ttf", size_in_pixels); // CORRECT
io.Fonts->AddFontFromFileTTF("MyDataFolder/MyFontFile.ttf", size_in_pixels); // ALSO CORRECT
Q: How can I easily use icons in my application?
A: The most convenient and practical way is to merge an icon font such as FontAwesome inside you
main font. Then you can refer to icons within your strings.
You may want to see ImFontConfig::GlyphMinAdvanceX to make your icon look monospace to facilitate alignment.
(Read the 'misc/fonts/README.txt' file for more details about icons font loading.)
Q: How can I load multiple fonts?
A: Use the font atlas to pack them into a single texture:
(Read the 'misc/fonts/README.txt' file and the code in ImFontAtlas for more details.)
ImGuiIO& io = ImGui::GetIO();
ImFont* font0 = io.Fonts->AddFontDefault();
ImFont* font1 = io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels);
ImFont* font2 = io.Fonts->AddFontFromFileTTF("myfontfile2.ttf", size_in_pixels);
io.Fonts->GetTexDataAsRGBA32() or GetTexDataAsAlpha8()
// the first loaded font gets used by default
// use ImGui::PushFont()/ImGui::PopFont() to change the font at runtime
// Options
ImFontConfig config;
config.OversampleH = 2;
config.OversampleV = 1;
config.GlyphOffset.y -= 1.0f; // Move everything by 1 pixels up
config.GlyphExtraSpacing.x = 1.0f; // Increase spacing between characters
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, &config);
// Combine multiple fonts into one (e.g. for icon fonts)
static ImWchar ranges[] = { 0xf000, 0xf3ff, 0 };
ImFontConfig config;
config.MergeMode = true;
io.Fonts->AddFontDefault();
io.Fonts->AddFontFromFileTTF("fontawesome-webfont.ttf", 16.0f, &config, ranges); // Merge icon font
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_pixels, NULL, &config, io.Fonts->GetGlyphRangesJapanese()); // Merge japanese glyphs
Q: How can I display and input non-Latin characters such as Chinese, Japanese, Korean, Cyrillic?
A: When loading a font, pass custom Unicode ranges to specify the glyphs to load.
// Add default Japanese ranges
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, io.Fonts->GetGlyphRangesJapanese());
// Or create your own custom ranges (e.g. for a game you can feed your entire game script and only build the characters the game need)
ImVector<ImWchar> ranges;
ImFontGlyphRangesBuilder builder;
builder.AddText("Hello world"); // Add a string (here "Hello world" contains 7 unique characters)
builder.AddChar(0x7262); // Add a specific character
builder.AddRanges(io.Fonts->GetGlyphRangesJapanese()); // Add one of the default ranges
builder.BuildRanges(&ranges); // Build the final result (ordered ranges with all the unique characters submitted)
io.Fonts->AddFontFromFileTTF("myfontfile.ttf", size_in_pixels, NULL, ranges.Data);
All your strings needs to use UTF-8 encoding. In C++11 you can encode a string literal in UTF-8
by using the u8"hello" syntax. Specifying literal in your source code using a local code page
(such as CP-923 for Japanese or CP-1251 for Cyrillic) will NOT work!
Otherwise you can convert yourself to UTF-8 or load text data from file already saved as UTF-8.
Text input: it is up to your application to pass the right character code by calling io.AddInputCharacter().
The applications in examples/ are doing that.
Windows: you can use the WM_CHAR or WM_UNICHAR or WM_IME_CHAR message (depending if your app is built using Unicode or MultiByte mode).
You may also use MultiByteToWideChar() or ToUnicode() to retrieve Unicode codepoints from MultiByte characters or keyboard state.
Windows: if your language is relying on an Input Method Editor (IME), you copy the HWND of your window to io.ImeWindowHandle in order for
the default implementation of io.ImeSetInputScreenPosFn() to set your Microsoft IME position correctly.
Q: How can I interact with standard C++ types (such as std::string and std::vector)?
A: - Being highly portable (bindings for several languages, frameworks, programming style, obscure or older platforms/compilers),
and aiming for compatibility & performance suitable for every modern real-time game engines, dear imgui does not use
any of std C++ types. We use raw types (e.g. char* instead of std::string) because they adapt to more use cases.
- To use ImGui::InputText() with a std::string or any resizable string class, see misc/cpp/imgui_stdlib.h.
- To use combo boxes and list boxes with std::vector or any other data structure: the BeginCombo()/EndCombo() API
lets you iterate and submit items yourself, so does the ListBoxHeader()/ListBoxFooter() API.
Prefer using them over the old and awkward Combo()/ListBox() api.
- Generally for most high-level types you should be able to access the underlying data type.
You may write your own one-liner wrappers to facilitate user code (tip: add new functions in ImGui:: namespace from your code).
- Dear ImGui applications often need to make intensive use of strings. It is expected that many of the strings you will pass
to the API are raw literals (free in C/C++) or allocated in a manner that won't incur a large cost on your application.
Please bear in mind that using std::string on applications with large amount of UI may incur unsatisfactory performances.
Modern implementations of std::string often include small-string optimization (which is often a local buffer) but those
are not configurable and not the same across implementations.
- If you are finding your UI traversal cost to be too large, make sure your string usage is not leading to excessive amount
of heap allocations. Consider using literals, statically sized buffers and your own helper functions. A common pattern
is that you will need to build lots of strings on the fly, and their maximum length can be easily be scoped ahead.
One possible implementation of a helper to facilitate printf-style building of strings: https://github.com/ocornut/Str
This is a small helper where you can instance strings with configurable local buffers length. Many game engines will
provide similar or better string helpers.
Q: How can I use the drawing facilities without an ImGui window? (using ImDrawList API)
A: - You can create a dummy window. Call Begin() with the NoBackground | NoDecoration | NoSavedSettings | NoInputs flags.
(The ImGuiWindowFlags_NoDecoration flag itself is a shortcut for NoTitleBar | NoResize | NoScrollbar | NoCollapse)
Then you can retrieve the ImDrawList* via GetWindowDrawList() and draw to it in any way you like.
- You can call ImGui::GetOverlayDrawList() and use this draw list to display contents over every other imgui windows (1 overlay per viewport).
- You can create your own ImDrawList instance. You'll need to initialize them ImGui::GetDrawListSharedData(), or create
your own ImDrawListSharedData, and then call your rendered code with your own ImDrawList or ImDrawData data.
Q: How can I use this without a mouse, without a keyboard or without a screen? (gamepad, input share, remote display)
A: - You can control Dear ImGui with a gamepad. Read about navigation in "Using gamepad/keyboard navigation controls".
(short version: map gamepad inputs into the io.NavInputs[] array + set io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad)
- You can share your computer mouse seamlessly with your console/tablet/phone using Synergy (https://symless.com/synergy)
This is the preferred solution for developer productivity.
In particular, the "micro-synergy-client" repository (https://github.com/symless/micro-synergy-client) has simple
and portable source code (uSynergy.c/.h) for a small embeddable client that you can use on any platform to connect
to your host computer, based on the Synergy 1.x protocol. Make sure you download the Synergy 1 server on your computer.
Console SDK also sometimes provide equivalent tooling or wrapper for Synergy-like protocols.
- You may also use a third party solution such as Remote ImGui (https://github.com/JordiRos/remoteimgui) which sends
the vertices to render over the local network, allowing you to use Dear ImGui even on a screen-less machine.
- For touch inputs, you can increase the hit box of widgets (via the style.TouchPadding setting) to accommodate
for the lack of precision of touch inputs, but it is recommended you use a mouse or gamepad to allow optimizing
for screen real-estate and precision.
Q: I integrated Dear ImGui in my engine and the text or lines are blurry..
A: In your Render function, try translating your projection matrix by (0.5f,0.5f) or (0.375f,0.375f).
Also make sure your orthographic projection matrix and io.DisplaySize matches your actual framebuffer dimension.
Q: I integrated Dear ImGui in my engine and some elements are clipping or disappearing when I move windows around..
A: You are probably mishandling the clipping rectangles in your render function.
Rectangles provided by ImGui are defined as (x1=left,y1=top,x2=right,y2=bottom) and NOT as (x1,y1,width,height).
Q: How can I help?
A: - If you are experienced with Dear ImGui and C++, look at the github issues, look at the Wiki, read docs/TODO.txt
and see how you want to help and can help!
- Businesses: convince your company to fund development via support contracts/sponsoring! This is among the most useful thing you can do for dear imgui.
- Individuals: you can also become a Patron (http://www.patreon.com/imgui) or donate on PayPal! See README.
- Disclose your usage of dear imgui via a dev blog post, a tweet, a screenshot, a mention somewhere etc.
You may post screenshot or links in the gallery threads (github.com/ocornut/imgui/issues/1902). Visuals are ideal as they inspire other programmers.
But even without visuals, disclosing your use of dear imgui help the library grow credibility, and help other teams and programmers with taking decisions.
- If you have issues or if you need to hack into the library, even if you don't expect any support it is useful that you share your issues (on github or privately).
- tip: you can call Begin() multiple times with the same name during the same frame, it will keep appending to the same window.
this is also useful to set yourself in the context of another window (to get/set other settings)
- tip: you can create widgets without a Begin()/End() block, they will go in an implicit window called "Debug".
- tip: the ImGuiOnceUponAFrame helper will allow run the block of code only once a frame. You can use it to quickly add custom UI in the middle
of a deep nested inner loop in your code.
- tip: you can call Render() multiple times (e.g for VR renders).
- tip: call and read the ShowDemoWindow() code in imgui_demo.cpp for more example of how to use ImGui!
*/
#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_WARNINGS)
#define _CRT_SECURE_NO_WARNINGS
#endif
#include "imgui.h"
#ifndef IMGUI_DEFINE_MATH_OPERATORS
#define IMGUI_DEFINE_MATH_OPERATORS
#endif
#include "imgui_internal.h"
#include <ctype.h> // toupper, isprint
#include <stdio.h> // vsnprintf, sscanf, printf
#if defined(_MSC_VER) && _MSC_VER <= 1500 // MSVC 2008 or earlier
#include <stddef.h> // intptr_t
#else
#include <stdint.h> // intptr_t
#endif
// Debug options
#define IMGUI_DEBUG_NAV_SCORING 0 // Display navigation scoring preview when hovering items. Display last moving direction matches when holding CTRL
#define IMGUI_DEBUG_NAV_RECTS 0 // Display the reference navigation rectangle for each window
#define IMGUI_DEBUG_DOCKING_INI 0 // Save additional comments in .ini file (makes saving slower)
// Visual Studio warnings
#ifdef _MSC_VER
#pragma warning (disable: 4127) // condition expression is constant
#pragma warning (disable: 4996) // 'This function or variable may be unsafe': strcpy, strdup, sprintf, vsnprintf, sscanf, fopen
#endif
// Clang/GCC warnings with -Weverything
#ifdef __clang__
#pragma clang diagnostic ignored "-Wunknown-pragmas" // warning : unknown warning group '-Wformat-pedantic *' // not all warnings are known by all clang versions.. so ignoring warnings triggers new warnings on some configuration. great!
#pragma clang diagnostic ignored "-Wold-style-cast" // warning : use of old-style cast // yes, they are more terse.
#pragma clang diagnostic ignored "-Wfloat-equal" // warning : comparing floating point with == or != is unsafe // storing and comparing against same constants (typically 0.0f) is ok.
#pragma clang diagnostic ignored "-Wformat-nonliteral" // warning : format string is not a string literal // passing non-literal to vsnformat(). yes, user passing incorrect format strings can crash the code.
#pragma clang diagnostic ignored "-Wexit-time-destructors" // warning : declaration requires an exit-time destructor // exit-time destruction order is undefined. if MemFree() leads to users code that has been disabled before exit it might cause problems. ImGui coding style welcomes static/globals.
#pragma clang diagnostic ignored "-Wglobal-constructors" // warning : declaration requires a global destructor // similar to above, not sure what the exact difference it.
#pragma clang diagnostic ignored "-Wsign-conversion" // warning : implicit conversion changes signedness //
#pragma clang diagnostic ignored "-Wformat-pedantic" // warning : format specifies type 'void *' but the argument has type 'xxxx *' // unreasonable, would lead to casting every %p arg to void*. probably enabled by -pedantic.
#pragma clang diagnostic ignored "-Wint-to-void-pointer-cast" // warning : cast to 'void *' from smaller integer type 'int'
#if __has_warning("-Wzero-as-null-pointer-constant")
#pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" // warning : zero as null pointer constant // some standard header variations use #define NULL 0
#endif
#if __has_warning("-Wdouble-promotion")
#pragma clang diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function // using printf() is a misery with this as C++ va_arg ellipsis changes float to double.
#endif
#elif defined(__GNUC__)
#pragma GCC diagnostic ignored "-Wunused-function" // warning: 'xxxx' defined but not used
#pragma GCC diagnostic ignored "-Wint-to-pointer-cast" // warning: cast to pointer from integer of different size
#pragma GCC diagnostic ignored "-Wformat" // warning: format '%p' expects argument of type 'void*', but argument 6 has type 'ImGuiWindow*'
#pragma GCC diagnostic ignored "-Wdouble-promotion" // warning: implicit conversion from 'float' to 'double' when passing argument to function
#pragma GCC diagnostic ignored "-Wconversion" // warning: conversion to 'xxxx' from 'xxxx' may alter its value
#pragma GCC diagnostic ignored "-Wformat-nonliteral" // warning: format not a string literal, format string not checked
#pragma GCC diagnostic ignored "-Wstrict-overflow" // warning: assuming signed overflow does not occur when assuming that (X - c) > X is always false
#if __GNUC__ >= 8
#pragma GCC diagnostic ignored "-Wclass-memaccess" // warning: 'memset/memcpy' clearing/writing an object of type 'xxxx' with no trivial copy-assignment; use assignment or value-initialization instead
#endif
#endif
// When using CTRL+TAB (or Gamepad Square+L/R) we delay the visual a little in order to reduce visual noise doing a fast switch.
static const float NAV_WINDOWING_HIGHLIGHT_DELAY = 0.20f; // Time before the highlight and screen dimming starts fading in
static const float NAV_WINDOWING_LIST_APPEAR_DELAY = 0.15f; // Time before the window list starts to appear
// Window resizing from edges (when io.ConfigWindowsResizeFromEdges = true and ImGuiBackendFlags_HasMouseCursors is set in io.BackendFlags by back-end)
static const float WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS = 4.0f; // Extend outside and inside windows. Affect FindHoveredWindow().
static const float WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER = 0.04f; // Reduce visual noise by only highlighting the border after a certain time.
// Docking
static const float DOCKING_TRANSPARENT_PAYLOAD_ALPHA = 0.50f; // For use with io.ConfigDockingTransparentPayload. Apply to Viewport _or_ WindowBg in host viewport.
//-------------------------------------------------------------------------
// [SECTION] FORWARD DECLARATIONS
//-------------------------------------------------------------------------
static void SetCurrentWindow(ImGuiWindow* window);
static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size);
static void FindHoveredWindow();
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags);
static void CheckStacksSize(ImGuiWindow* window, bool write);
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges);
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list);
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window);
// Settings
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
// Platform Dependents default implementation for IO functions
static const char* GetClipboardTextFn_DefaultImpl(void* user_data);
static void SetClipboardTextFn_DefaultImpl(void* user_data, const char* text);
namespace ImGui
{
static bool BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags);
// Navigation
static void NavUpdate();
static void NavUpdateWindowing();
static void NavUpdateWindowingList();
static void NavUpdateMoveResult();
static float NavUpdatePageUpPageDown(int allowed_dir_flags);
static inline void NavUpdateAnyRequestFlag();
static void NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id);
static ImVec2 NavCalcPreferredRefPos();
static void NavSaveLastChildNavWindow(ImGuiWindow* nav_window);
static ImGuiWindow* NavRestoreLastChildNavWindow(ImGuiWindow* window);
// Misc
static void UpdateMouseInputs();
static void UpdateMouseWheel();
static void UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4]);
static void RenderOuterBorders(ImGuiWindow* window);
static void EndFrameDrawDimmedBackgrounds();
// Viewports
const ImGuiID IMGUI_VIEWPORT_DEFAULT_ID = 0x11111111; // Using an arbitrary constant instead of e.g. ImHashStr("ViewportDefault", 0); so it's easier to spot in the debugger. The exact value doesn't matter.
static ImGuiViewportP* AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& platform_pos, const ImVec2& size, ImGuiViewportFlags flags);
static void UpdateViewportsNewFrame();
static void UpdateViewportsEndFrame();
static void UpdateSelectWindowViewport(ImGuiWindow* window);
static bool UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* host_viewport);
static void SetCurrentViewport(ImGuiWindow* window, ImGuiViewportP* viewport);
static bool GetWindowAlwaysWantOwnViewport(ImGuiWindow* window);
static int FindPlatformMonitorForPos(const ImVec2& pos);
static int FindPlatformMonitorForRect(const ImRect& r);
}
//-----------------------------------------------------------------------------
// [SECTION] CONTEXT AND MEMORY ALLOCATORS
//-----------------------------------------------------------------------------
// Current context pointer. Implicitly used by all Dear ImGui functions. Always assumed to be != NULL.
// ImGui::CreateContext() will automatically set this pointer if it is NULL. Change to a different context by calling ImGui::SetCurrentContext().
// 1) Important: globals are not shared across DLL boundaries! If you use DLLs or any form of hot-reloading: you will need to call
// SetCurrentContext() (with the pointer you got from CreateContext) from each unique static/DLL boundary, and after each hot-reloading.
// In your debugger, add GImGui to your watch window and notice how its value changes depending on which location you are currently stepping into.
// 2) Important: Dear ImGui functions are not thread-safe because of this pointer.
// If you want thread-safety to allow N threads to access N different contexts, you can:
// - Change this variable to use thread local storage so each thread can refer to a different context, in imconfig.h:
// struct ImGuiContext;
// extern thread_local ImGuiContext* MyImGuiTLS;
// #define GImGui MyImGuiTLS
// And then define MyImGuiTLS in one of your cpp file. Note that thread_local is a C++11 keyword, earlier C++ uses compiler-specific keyword.
// - Future development aim to make this context pointer explicit to all calls. Also read https://github.com/ocornut/imgui/issues/586
// - If you need a finite number of contexts, you may compile and use multiple instances of the ImGui code from different namespace.
#ifndef GImGui
ImGuiContext* GImGui = NULL;
#endif
// Memory Allocator functions. Use SetAllocatorFunctions() to change them.
// If you use DLL hotreloading you might need to call SetAllocatorFunctions() after reloading code from this file.
// Otherwise, you probably don't want to modify them mid-program, and if you use global/static e.g. ImVector<> instances you may need to keep them accessible during program destruction.
#ifndef IMGUI_DISABLE_DEFAULT_ALLOCATORS
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); return malloc(size); }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); free(ptr); }
#else
static void* MallocWrapper(size_t size, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(size); IM_ASSERT(0); return NULL; }
static void FreeWrapper(void* ptr, void* user_data) { IM_UNUSED(user_data); IM_UNUSED(ptr); IM_ASSERT(0); }
#endif
static void* (*GImAllocatorAllocFunc)(size_t size, void* user_data) = MallocWrapper;
static void (*GImAllocatorFreeFunc)(void* ptr, void* user_data) = FreeWrapper;
static void* GImAllocatorUserData = NULL;
//-----------------------------------------------------------------------------
// [SECTION] MAIN USER FACING STRUCTURES (ImGuiStyle, ImGuiIO)
//-----------------------------------------------------------------------------
ImGuiStyle::ImGuiStyle()
{
Alpha = 1.0f; // Global alpha applies to everything in ImGui
WindowPadding = ImVec2(8,8); // Padding within a window
WindowRounding = 7.0f; // Radius of window corners rounding. Set to 0.0f to have rectangular windows
WindowBorderSize = 1.0f; // Thickness of border around windows. Generally set to 0.0f or 1.0f. Other values not well tested.
WindowMinSize = ImVec2(32,32); // Minimum window size
WindowTitleAlign = ImVec2(0.0f,0.5f);// Alignment for title bar text
ChildRounding = 0.0f; // Radius of child window corners rounding. Set to 0.0f to have rectangular child windows
ChildBorderSize = 1.0f; // Thickness of border around child windows. Generally set to 0.0f or 1.0f. Other values not well tested.
PopupRounding = 0.0f; // Radius of popup window corners rounding. Set to 0.0f to have rectangular child windows
PopupBorderSize = 1.0f; // Thickness of border around popup or tooltip windows. Generally set to 0.0f or 1.0f. Other values not well tested.
FramePadding = ImVec2(4,3); // Padding within a framed rectangle (used by most widgets)
FrameRounding = 0.0f; // Radius of frame corners rounding. Set to 0.0f to have rectangular frames (used by most widgets).
FrameBorderSize = 0.0f; // Thickness of border around frames. Generally set to 0.0f or 1.0f. Other values not well tested.
ItemSpacing = ImVec2(8,4); // Horizontal and vertical spacing between widgets/lines
ItemInnerSpacing = ImVec2(4,4); // Horizontal and vertical spacing between within elements of a composed widget (e.g. a slider and its label)
TouchExtraPadding = ImVec2(0,0); // Expand reactive bounding box for touch-based system where touch position is not accurate enough. Unfortunately we don't sort widgets so priority on overlap will always be given to the first widget. So don't grow this too much!
IndentSpacing = 21.0f; // Horizontal spacing when e.g. entering a tree node. Generally == (FontSize + FramePadding.x*2).
ColumnsMinSpacing = 6.0f; // Minimum horizontal spacing between two columns
ScrollbarSize = 16.0f; // Width of the vertical scrollbar, Height of the horizontal scrollbar
ScrollbarRounding = 9.0f; // Radius of grab corners rounding for scrollbar
GrabMinSize = 10.0f; // Minimum width/height of a grab box for slider/scrollbar
GrabRounding = 0.0f; // Radius of grabs corners rounding. Set to 0.0f to have rectangular slider grabs.
TabRounding = 4.0f; // Radius of upper corners of a tab. Set to 0.0f to have rectangular tabs.
TabBorderSize = 0.0f; // Thickness of border around tabs.
ButtonTextAlign = ImVec2(0.5f,0.5f);// Alignment of button text when button is larger than text.
SelectableTextAlign = ImVec2(0.0f,0.0f);// Alignment of selectable text when button is larger than text.
DisplayWindowPadding = ImVec2(19,19); // Window position are clamped to be visible within the display area or monitors by at least this amount. Only applies to regular windows.
DisplaySafeAreaPadding = ImVec2(3,3); // If you cannot see the edge of your screen (e.g. on a TV) increase the safe area padding. Covers popups/tooltips as well regular windows.
MouseCursorScale = 1.0f; // Scale software rendered mouse cursor (when io.MouseDrawCursor is enabled). May be removed later.
AntiAliasedLines = true; // Enable anti-aliasing on lines/borders. Disable if you are really short on CPU/GPU.
AntiAliasedFill = true; // Enable anti-aliasing on filled shapes (rounded rectangles, circles, etc.)
CurveTessellationTol = 1.25f; // Tessellation tolerance when using PathBezierCurveTo() without a specific number of segments. Decrease for highly tessellated curves (higher quality, more polygons), increase to reduce quality.
// Default theme
ImGui::StyleColorsDark(this);
}
// To scale your entire UI (e.g. if you want your app to use High DPI or generally be DPI aware) you may use this helper function. Scaling the fonts is done separately and is up to you.
// Important: This operation is lossy because we round all sizes to integer. If you need to change your scale multiples, call this over a freshly initialized ImGuiStyle structure rather than scaling multiple times.
void ImGuiStyle::ScaleAllSizes(float scale_factor)
{
WindowPadding = ImFloor(WindowPadding * scale_factor);
WindowRounding = ImFloor(WindowRounding * scale_factor);
WindowMinSize = ImFloor(WindowMinSize * scale_factor);
ChildRounding = ImFloor(ChildRounding * scale_factor);
PopupRounding = ImFloor(PopupRounding * scale_factor);
FramePadding = ImFloor(FramePadding * scale_factor);
FrameRounding = ImFloor(FrameRounding * scale_factor);
ItemSpacing = ImFloor(ItemSpacing * scale_factor);
ItemInnerSpacing = ImFloor(ItemInnerSpacing * scale_factor);
TouchExtraPadding = ImFloor(TouchExtraPadding * scale_factor);
IndentSpacing = ImFloor(IndentSpacing * scale_factor);
ColumnsMinSpacing = ImFloor(ColumnsMinSpacing * scale_factor);
ScrollbarSize = ImFloor(ScrollbarSize * scale_factor);
ScrollbarRounding = ImFloor(ScrollbarRounding * scale_factor);
GrabMinSize = ImFloor(GrabMinSize * scale_factor);
GrabRounding = ImFloor(GrabRounding * scale_factor);
TabRounding = ImFloor(TabRounding * scale_factor);
DisplayWindowPadding = ImFloor(DisplayWindowPadding * scale_factor);
DisplaySafeAreaPadding = ImFloor(DisplaySafeAreaPadding * scale_factor);
MouseCursorScale = ImFloor(MouseCursorScale * scale_factor);
}
ImGuiIO::ImGuiIO()
{
// Most fields are initialized with zero
memset(this, 0, sizeof(*this));
// Settings
ConfigFlags = ImGuiConfigFlags_None;
BackendFlags = ImGuiBackendFlags_None;
DisplaySize = ImVec2(-1.0f, -1.0f);
DeltaTime = 1.0f/60.0f;
IniSavingRate = 5.0f;
IniFilename = "imgui.ini";
LogFilename = "imgui_log.txt";
MouseDoubleClickTime = 0.30f;
MouseDoubleClickMaxDist = 6.0f;
for (int i = 0; i < ImGuiKey_COUNT; i++)
KeyMap[i] = -1;
KeyRepeatDelay = 0.250f;
KeyRepeatRate = 0.050f;
UserData = NULL;
Fonts = NULL;
FontGlobalScale = 1.0f;
FontDefault = NULL;
FontAllowUserScaling = false;
DisplayFramebufferScale = ImVec2(1.0f, 1.0f);
// Docking options (when ImGuiConfigFlags_DockingEnable is set)
ConfigDockingNoSplit = false;
ConfigDockingWithShift = false;
ConfigDockingTabBarOnSingleWindows = false;
ConfigDockingTransparentPayload = false;
// Viewport options (when ImGuiConfigFlags_ViewportsEnable is set)
ConfigViewportsNoAutoMerge = false;
ConfigViewportsNoTaskBarIcon = false;
ConfigViewportsNoDecoration = true;
ConfigViewportsNoParent = false;
// Miscellaneous options
MouseDrawCursor = false;
#ifdef __APPLE__
ConfigMacOSXBehaviors = true; // Set Mac OS X style defaults based on __APPLE__ compile time flag
#else
ConfigMacOSXBehaviors = false;
#endif
ConfigInputTextCursorBlink = true;
ConfigWindowsResizeFromEdges = true;
ConfigWindowsMoveFromTitleBarOnly = false;
// Platform Functions
BackendPlatformName = BackendRendererName = NULL;
BackendPlatformUserData = BackendRendererUserData = BackendLanguageUserData = NULL;
GetClipboardTextFn = GetClipboardTextFn_DefaultImpl; // Platform dependent default implementations
SetClipboardTextFn = SetClipboardTextFn_DefaultImpl;
ClipboardUserData = NULL;
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
RenderDrawListsFn = NULL;
#endif
// Input (NB: we already have memset zero the entire structure!)
MousePos = ImVec2(-FLT_MAX, -FLT_MAX);
MousePosPrev = ImVec2(-FLT_MAX, -FLT_MAX);
MouseDragThreshold = 6.0f;
for (int i = 0; i < IM_ARRAYSIZE(MouseDownDuration); i++) MouseDownDuration[i] = MouseDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(KeysDownDuration); i++) KeysDownDuration[i] = KeysDownDurationPrev[i] = -1.0f;
for (int i = 0; i < IM_ARRAYSIZE(NavInputsDownDuration); i++) NavInputsDownDuration[i] = -1.0f;
}
// Pass in translated ASCII characters for text input.
// - with glfw you can get those from the callback set in glfwSetCharCallback()
// - on Windows you can get those using ToAscii+keyboard state, or via the WM_CHAR message
void ImGuiIO::AddInputCharacter(ImWchar c)
{
InputQueueCharacters.push_back(c);
}
void ImGuiIO::AddInputCharactersUTF8(const char* utf8_chars)
{
while (*utf8_chars != 0)
{
unsigned int c = 0;
utf8_chars += ImTextCharFromUtf8(&c, utf8_chars, NULL);
if (c > 0 && c <= 0xFFFF)
InputQueueCharacters.push_back((ImWchar)c);
}
}
void ImGuiIO::ClearInputCharacters()
{
InputQueueCharacters.resize(0);
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPER/UTILITIES (Maths, String, Format, Hash, File functions)
//-----------------------------------------------------------------------------
ImVec2 ImLineClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& p)
{
ImVec2 ap = p - a;
ImVec2 ab_dir = b - a;
float dot = ap.x * ab_dir.x + ap.y * ab_dir.y;
if (dot < 0.0f)
return a;
float ab_len_sqr = ab_dir.x * ab_dir.x + ab_dir.y * ab_dir.y;
if (dot > ab_len_sqr)
return b;
return a + ab_dir * dot / ab_len_sqr;
}
bool ImTriangleContainsPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
bool b1 = ((p.x - b.x) * (a.y - b.y) - (p.y - b.y) * (a.x - b.x)) < 0.0f;
bool b2 = ((p.x - c.x) * (b.y - c.y) - (p.y - c.y) * (b.x - c.x)) < 0.0f;
bool b3 = ((p.x - a.x) * (c.y - a.y) - (p.y - a.y) * (c.x - a.x)) < 0.0f;
return ((b1 == b2) && (b2 == b3));
}
void ImTriangleBarycentricCoords(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p, float& out_u, float& out_v, float& out_w)
{
ImVec2 v0 = b - a;
ImVec2 v1 = c - a;
ImVec2 v2 = p - a;
const float denom = v0.x * v1.y - v1.x * v0.y;
out_v = (v2.x * v1.y - v1.x * v2.y) / denom;
out_w = (v0.x * v2.y - v2.x * v0.y) / denom;
out_u = 1.0f - out_v - out_w;
}
ImVec2 ImTriangleClosestPoint(const ImVec2& a, const ImVec2& b, const ImVec2& c, const ImVec2& p)
{
ImVec2 proj_ab = ImLineClosestPoint(a, b, p);
ImVec2 proj_bc = ImLineClosestPoint(b, c, p);
ImVec2 proj_ca = ImLineClosestPoint(c, a, p);
float dist2_ab = ImLengthSqr(p - proj_ab);
float dist2_bc = ImLengthSqr(p - proj_bc);
float dist2_ca = ImLengthSqr(p - proj_ca);
float m = ImMin(dist2_ab, ImMin(dist2_bc, dist2_ca));
if (m == dist2_ab)
return proj_ab;
if (m == dist2_bc)
return proj_bc;
return proj_ca;
}
// Consider using _stricmp/_strnicmp under Windows or strcasecmp/strncasecmp. We don't actually use either ImStricmp/ImStrnicmp in the codebase any more.
int ImStricmp(const char* str1, const char* str2)
{
int d;
while ((d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; }
return d;
}
int ImStrnicmp(const char* str1, const char* str2, size_t count)
{
int d = 0;
while (count > 0 && (d = toupper(*str2) - toupper(*str1)) == 0 && *str1) { str1++; str2++; count--; }
return d;
}
void ImStrncpy(char* dst, const char* src, size_t count)
{
if (count < 1)
return;
if (count > 1)
strncpy(dst, src, count - 1);
dst[count - 1] = 0;
}
char* ImStrdup(const char* str)
{
size_t len = strlen(str);
void* buf = ImGui::MemAlloc(len + 1);
return (char*)memcpy(buf, (const void*)str, len + 1);
}
char* ImStrdupcpy(char* dst, size_t* p_dst_size, const char* src)
{
size_t dst_buf_size = p_dst_size ? *p_dst_size : strlen(dst) + 1;
size_t src_size = strlen(src) + 1;
if (dst_buf_size < src_size)
{
ImGui::MemFree(dst);
dst = (char*)ImGui::MemAlloc(src_size);
if (p_dst_size)
*p_dst_size = src_size;
}
return (char*)memcpy(dst, (const void*)src, src_size);
}
const char* ImStrchrRange(const char* str, const char* str_end, char c)
{
const char* p = (const char*)memchr(str, (int)c, str_end - str);
return p;
}
int ImStrlenW(const ImWchar* str)
{
//return (int)wcslen((const wchar_t*)str); // FIXME-OPT: Could use this when wchar_t are 16-bits
int n = 0;
while (*str++) n++;
return n;
}
// Find end-of-line. Return pointer will point to either first \n, either str_end.
const char* ImStreolRange(const char* str, const char* str_end)
{
const char* p = (const char*)memchr(str, '\n', str_end - str);
return p ? p : str_end;
}
const ImWchar* ImStrbolW(const ImWchar* buf_mid_line, const ImWchar* buf_begin) // find beginning-of-line
{
while (buf_mid_line > buf_begin && buf_mid_line[-1] != '\n')
buf_mid_line--;
return buf_mid_line;
}
const char* ImStristr(const char* haystack, const char* haystack_end, const char* needle, const char* needle_end)
{
if (!needle_end)
needle_end = needle + strlen(needle);
const char un0 = (char)toupper(*needle);
while ((!haystack_end && *haystack) || (haystack_end && haystack < haystack_end))
{
if (toupper(*haystack) == un0)
{
const char* b = needle + 1;
for (const char* a = haystack + 1; b < needle_end; a++, b++)
if (toupper(*a) != toupper(*b))
break;
if (b == needle_end)
return haystack;
}
haystack++;
}
return NULL;
}
// Trim str by offsetting contents when there's leading data + writing a \0 at the trailing position. We use this in situation where the cost is negligible.
void ImStrTrimBlanks(char* buf)
{
char* p = buf;
while (p[0] == ' ' || p[0] == '\t') // Leading blanks
p++;
char* p_start = p;
while (*p != 0) // Find end of string
p++;
while (p > p_start && (p[-1] == ' ' || p[-1] == '\t')) // Trailing blanks
p--;
if (p_start != buf) // Copy memory if we had leading blanks
memmove(buf, p_start, p - p_start);
buf[p - p_start] = 0; // Zero terminate
}
const char* ImStrSkipBlank(const char* str)
{
while (str[0] == ' ' || str[0] == '\t')
str++;
return str;
}
// A) MSVC version appears to return -1 on overflow, whereas glibc appears to return total count (which may be >= buf_size).
// Ideally we would test for only one of those limits at runtime depending on the behavior the vsnprintf(), but trying to deduct it at compile time sounds like a pandora can of worm.
// B) When buf==NULL vsnprintf() will return the output size.
#ifndef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
//#define IMGUI_USE_STB_SPRINTF
#ifdef IMGUI_USE_STB_SPRINTF
#define STB_SPRINTF_IMPLEMENTATION
#include "imstb_sprintf.h"
#endif
#if defined(_MSC_VER) && !defined(vsnprintf)
#define vsnprintf _vsnprintf
#endif
int ImFormatString(char* buf, size_t buf_size, const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
va_end(args);
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
int ImFormatStringV(char* buf, size_t buf_size, const char* fmt, va_list args)
{
#ifdef IMGUI_USE_STB_SPRINTF
int w = stbsp_vsnprintf(buf, (int)buf_size, fmt, args);
#else
int w = vsnprintf(buf, buf_size, fmt, args);
#endif
if (buf == NULL)
return w;
if (w == -1 || w >= (int)buf_size)
w = (int)buf_size - 1;
buf[w] = 0;
return w;
}
#endif // #ifdef IMGUI_DISABLE_FORMAT_STRING_FUNCTIONS
// CRC32 needs a 1KB lookup table (not cache friendly)
// Although the code to generate the table is simple and shorter than the table itself, using a const table allows us to easily:
// - avoid an unnecessary branch/memory tap, - keep the ImHashXXX functions usable by static constructors, - make it thread-safe.
static const ImU32 GCrc32LookupTable[256] =
{
0x00000000,0x77073096,0xEE0E612C,0x990951BA,0x076DC419,0x706AF48F,0xE963A535,0x9E6495A3,0x0EDB8832,0x79DCB8A4,0xE0D5E91E,0x97D2D988,0x09B64C2B,0x7EB17CBD,0xE7B82D07,0x90BF1D91,
0x1DB71064,0x6AB020F2,0xF3B97148,0x84BE41DE,0x1ADAD47D,0x6DDDE4EB,0xF4D4B551,0x83D385C7,0x136C9856,0x646BA8C0,0xFD62F97A,0x8A65C9EC,0x14015C4F,0x63066CD9,0xFA0F3D63,0x8D080DF5,
0x3B6E20C8,0x4C69105E,0xD56041E4,0xA2677172,0x3C03E4D1,0x4B04D447,0xD20D85FD,0xA50AB56B,0x35B5A8FA,0x42B2986C,0xDBBBC9D6,0xACBCF940,0x32D86CE3,0x45DF5C75,0xDCD60DCF,0xABD13D59,
0x26D930AC,0x51DE003A,0xC8D75180,0xBFD06116,0x21B4F4B5,0x56B3C423,0xCFBA9599,0xB8BDA50F,0x2802B89E,0x5F058808,0xC60CD9B2,0xB10BE924,0x2F6F7C87,0x58684C11,0xC1611DAB,0xB6662D3D,
0x76DC4190,0x01DB7106,0x98D220BC,0xEFD5102A,0x71B18589,0x06B6B51F,0x9FBFE4A5,0xE8B8D433,0x7807C9A2,0x0F00F934,0x9609A88E,0xE10E9818,0x7F6A0DBB,0x086D3D2D,0x91646C97,0xE6635C01,
0x6B6B51F4,0x1C6C6162,0x856530D8,0xF262004E,0x6C0695ED,0x1B01A57B,0x8208F4C1,0xF50FC457,0x65B0D9C6,0x12B7E950,0x8BBEB8EA,0xFCB9887C,0x62DD1DDF,0x15DA2D49,0x8CD37CF3,0xFBD44C65,
0x4DB26158,0x3AB551CE,0xA3BC0074,0xD4BB30E2,0x4ADFA541,0x3DD895D7,0xA4D1C46D,0xD3D6F4FB,0x4369E96A,0x346ED9FC,0xAD678846,0xDA60B8D0,0x44042D73,0x33031DE5,0xAA0A4C5F,0xDD0D7CC9,
0x5005713C,0x270241AA,0xBE0B1010,0xC90C2086,0x5768B525,0x206F85B3,0xB966D409,0xCE61E49F,0x5EDEF90E,0x29D9C998,0xB0D09822,0xC7D7A8B4,0x59B33D17,0x2EB40D81,0xB7BD5C3B,0xC0BA6CAD,
0xEDB88320,0x9ABFB3B6,0x03B6E20C,0x74B1D29A,0xEAD54739,0x9DD277AF,0x04DB2615,0x73DC1683,0xE3630B12,0x94643B84,0x0D6D6A3E,0x7A6A5AA8,0xE40ECF0B,0x9309FF9D,0x0A00AE27,0x7D079EB1,
0xF00F9344,0x8708A3D2,0x1E01F268,0x6906C2FE,0xF762575D,0x806567CB,0x196C3671,0x6E6B06E7,0xFED41B76,0x89D32BE0,0x10DA7A5A,0x67DD4ACC,0xF9B9DF6F,0x8EBEEFF9,0x17B7BE43,0x60B08ED5,
0xD6D6A3E8,0xA1D1937E,0x38D8C2C4,0x4FDFF252,0xD1BB67F1,0xA6BC5767,0x3FB506DD,0x48B2364B,0xD80D2BDA,0xAF0A1B4C,0x36034AF6,0x41047A60,0xDF60EFC3,0xA867DF55,0x316E8EEF,0x4669BE79,
0xCB61B38C,0xBC66831A,0x256FD2A0,0x5268E236,0xCC0C7795,0xBB0B4703,0x220216B9,0x5505262F,0xC5BA3BBE,0xB2BD0B28,0x2BB45A92,0x5CB36A04,0xC2D7FFA7,0xB5D0CF31,0x2CD99E8B,0x5BDEAE1D,
0x9B64C2B0,0xEC63F226,0x756AA39C,0x026D930A,0x9C0906A9,0xEB0E363F,0x72076785,0x05005713,0x95BF4A82,0xE2B87A14,0x7BB12BAE,0x0CB61B38,0x92D28E9B,0xE5D5BE0D,0x7CDCEFB7,0x0BDBDF21,
0x86D3D2D4,0xF1D4E242,0x68DDB3F8,0x1FDA836E,0x81BE16CD,0xF6B9265B,0x6FB077E1,0x18B74777,0x88085AE6,0xFF0F6A70,0x66063BCA,0x11010B5C,0x8F659EFF,0xF862AE69,0x616BFFD3,0x166CCF45,
0xA00AE278,0xD70DD2EE,0x4E048354,0x3903B3C2,0xA7672661,0xD06016F7,0x4969474D,0x3E6E77DB,0xAED16A4A,0xD9D65ADC,0x40DF0B66,0x37D83BF0,0xA9BCAE53,0xDEBB9EC5,0x47B2CF7F,0x30B5FFE9,
0xBDBDF21C,0xCABAC28A,0x53B39330,0x24B4A3A6,0xBAD03605,0xCDD70693,0x54DE5729,0x23D967BF,0xB3667A2E,0xC4614AB8,0x5D681B02,0x2A6F2B94,0xB40BBE37,0xC30C8EA1,0x5A05DF1B,0x2D02EF8D,
};
// Known size hash
// It is ok to call ImHashData on a string with known length but the ### operator won't be supported.
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashData(const void* data_p, size_t data_size, ImU32 seed)
{
ImU32 crc = ~seed;
const unsigned char* data = (const unsigned char*)data_p;
const ImU32* crc32_lut = GCrc32LookupTable;
while (data_size-- != 0)
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ *data++];
return ~crc;
}
// Zero-terminated string hash, with support for ### to reset back to seed value
// We support a syntax of "label###id" where only "###id" is included in the hash, and only "label" gets displayed.
// Because this syntax is rarely used we are optimizing for the common case.
// - If we reach ### in the string we discard the hash so far and reset to the seed.
// - We don't do 'current += 2; continue;' after handling ### to keep the code smaller/faster (measured ~10% diff in Debug build)
// FIXME-OPT: Replace with e.g. FNV1a hash? CRC32 pretty much randomly access 1KB. Need to do proper measurements.
ImU32 ImHashStr(const char* data, size_t data_size, ImU32 seed)
{
seed = ~seed;
ImU32 crc = seed;
const unsigned char* src = (const unsigned char*)data;
const ImU32* crc32_lut = GCrc32LookupTable;
if (data_size != 0)
{
while (data_size-- != 0)
{
unsigned char c = *src++;
if (c == '#' && src[0] == '#' && src[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
else
{
while (unsigned char c = *src++)
{
if (c == '#' && src[0] == '#' && src[1] == '#')
crc = seed;
crc = (crc >> 8) ^ crc32_lut[(crc & 0xFF) ^ c];
}
}
return ~crc;
}
FILE* ImFileOpen(const char* filename, const char* mode)
{
#if defined(_WIN32) && !defined(__CYGWIN__) && !defined(__GNUC__)
// We need a fopen() wrapper because MSVC/Windows fopen doesn't handle UTF-8 filenames. Converting both strings from UTF-8 to wchar format (using a single allocation, because we can)
const int filename_wsize = ImTextCountCharsFromUtf8(filename, NULL) + 1;
const int mode_wsize = ImTextCountCharsFromUtf8(mode, NULL) + 1;
ImVector<ImWchar> buf;
buf.resize(filename_wsize + mode_wsize);
ImTextStrFromUtf8(&buf[0], filename_wsize, filename, NULL);
ImTextStrFromUtf8(&buf[filename_wsize], mode_wsize, mode, NULL);
return _wfopen((wchar_t*)&buf[0], (wchar_t*)&buf[filename_wsize]);
#else
return fopen(filename, mode);
#endif
}
// Load file content into memory
// Memory allocated with ImGui::MemAlloc(), must be freed by user using ImGui::MemFree()
void* ImFileLoadToMemory(const char* filename, const char* file_open_mode, size_t* out_file_size, int padding_bytes)
{
IM_ASSERT(filename && file_open_mode);
if (out_file_size)
*out_file_size = 0;
FILE* f;
if ((f = ImFileOpen(filename, file_open_mode)) == NULL)
return NULL;
long file_size_signed;
if (fseek(f, 0, SEEK_END) || (file_size_signed = ftell(f)) == -1 || fseek(f, 0, SEEK_SET))
{
fclose(f);
return NULL;
}
size_t file_size = (size_t)file_size_signed;
void* file_data = ImGui::MemAlloc(file_size + padding_bytes);
if (file_data == NULL)
{
fclose(f);
return NULL;
}
if (fread(file_data, 1, file_size, f) != file_size)
{
fclose(f);
ImGui::MemFree(file_data);
return NULL;
}
if (padding_bytes > 0)
memset((void*)(((char*)file_data) + file_size), 0, (size_t)padding_bytes);
fclose(f);
if (out_file_size)
*out_file_size = file_size;
return file_data;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPERS/UTILITIES (ImText* functions)
//-----------------------------------------------------------------------------
// Convert UTF-8 to 32-bits character, process single character input.
// Based on stb_from_utf8() from github.com/nothings/stb/
// We handle UTF-8 decoding error by skipping forward.
int ImTextCharFromUtf8(unsigned int* out_char, const char* in_text, const char* in_text_end)
{
unsigned int c = (unsigned int)-1;
const unsigned char* str = (const unsigned char*)in_text;
if (!(*str & 0x80))
{
c = (unsigned int)(*str++);
*out_char = c;
return 1;
}
if ((*str & 0xe0) == 0xc0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 2) return 1;
if (*str < 0xc2) return 2;
c = (unsigned int)((*str++ & 0x1f) << 6);
if ((*str & 0xc0) != 0x80) return 2;
c += (*str++ & 0x3f);
*out_char = c;
return 2;
}
if ((*str & 0xf0) == 0xe0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 3) return 1;
if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return 3;
if (*str == 0xed && str[1] > 0x9f) return 3; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x0f) << 12);
if ((*str & 0xc0) != 0x80) return 3;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 3;
c += (*str++ & 0x3f);
*out_char = c;
return 3;
}
if ((*str & 0xf8) == 0xf0)
{
*out_char = 0xFFFD; // will be invalid but not end of string
if (in_text_end && in_text_end - (const char*)str < 4) return 1;
if (*str > 0xf4) return 4;
if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return 4;
if (*str == 0xf4 && str[1] > 0x8f) return 4; // str[1] < 0x80 is checked below
c = (unsigned int)((*str++ & 0x07) << 18);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 12);
if ((*str & 0xc0) != 0x80) return 4;
c += (unsigned int)((*str++ & 0x3f) << 6);
if ((*str & 0xc0) != 0x80) return 4;
c += (*str++ & 0x3f);
// utf-8 encodings of values used in surrogate pairs are invalid
if ((c & 0xFFFFF800) == 0xD800) return 4;
*out_char = c;
return 4;
}
*out_char = 0;
return 0;
}
int ImTextStrFromUtf8(ImWchar* buf, int buf_size, const char* in_text, const char* in_text_end, const char** in_text_remaining)
{
ImWchar* buf_out = buf;
ImWchar* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000) // FIXME: Losing characters that don't fit in 2 bytes
*buf_out++ = (ImWchar)c;
}
*buf_out = 0;
if (in_text_remaining)
*in_text_remaining = in_text;
return (int)(buf_out - buf);
}
int ImTextCountCharsFromUtf8(const char* in_text, const char* in_text_end)
{
int char_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c;
in_text += ImTextCharFromUtf8(&c, in_text, in_text_end);
if (c == 0)
break;
if (c < 0x10000)
char_count++;
}
return char_count;
}
// Based on stb_to_utf8() from github.com/nothings/stb/
static inline int ImTextCharToUtf8(char* buf, int buf_size, unsigned int c)
{
if (c < 0x80)
{
buf[0] = (char)c;
return 1;
}
if (c < 0x800)
{
if (buf_size < 2) return 0;
buf[0] = (char)(0xc0 + (c >> 6));
buf[1] = (char)(0x80 + (c & 0x3f));
return 2;
}
if (c >= 0xdc00 && c < 0xe000)
{
return 0;
}
if (c >= 0xd800 && c < 0xdc00)
{
if (buf_size < 4) return 0;
buf[0] = (char)(0xf0 + (c >> 18));
buf[1] = (char)(0x80 + ((c >> 12) & 0x3f));
buf[2] = (char)(0x80 + ((c >> 6) & 0x3f));
buf[3] = (char)(0x80 + ((c ) & 0x3f));
return 4;
}
//else if (c < 0x10000)
{
if (buf_size < 3) return 0;
buf[0] = (char)(0xe0 + (c >> 12));
buf[1] = (char)(0x80 + ((c>> 6) & 0x3f));
buf[2] = (char)(0x80 + ((c ) & 0x3f));
return 3;
}
}
// Not optimal but we very rarely use this function.
int ImTextCountUtf8BytesFromChar(const char* in_text, const char* in_text_end)
{
unsigned int dummy = 0;
return ImTextCharFromUtf8(&dummy, in_text, in_text_end);
}
static inline int ImTextCountUtf8BytesFromChar(unsigned int c)
{
if (c < 0x80) return 1;
if (c < 0x800) return 2;
if (c >= 0xdc00 && c < 0xe000) return 0;
if (c >= 0xd800 && c < 0xdc00) return 4;
return 3;
}
int ImTextStrToUtf8(char* buf, int buf_size, const ImWchar* in_text, const ImWchar* in_text_end)
{
char* buf_out = buf;
const char* buf_end = buf + buf_size;
while (buf_out < buf_end-1 && (!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
*buf_out++ = (char)c;
else
buf_out += ImTextCharToUtf8(buf_out, (int)(buf_end-buf_out-1), c);
}
*buf_out = 0;
return (int)(buf_out - buf);
}
int ImTextCountUtf8BytesFromStr(const ImWchar* in_text, const ImWchar* in_text_end)
{
int bytes_count = 0;
while ((!in_text_end || in_text < in_text_end) && *in_text)
{
unsigned int c = (unsigned int)(*in_text++);
if (c < 0x80)
bytes_count++;
else
bytes_count += ImTextCountUtf8BytesFromChar(c);
}
return bytes_count;
}
//-----------------------------------------------------------------------------
// [SECTION] MISC HELPER/UTILTIES (Color functions)
// Note: The Convert functions are early design which are not consistent with other API.
//-----------------------------------------------------------------------------
ImVec4 ImGui::ColorConvertU32ToFloat4(ImU32 in)
{
float s = 1.0f/255.0f;
return ImVec4(
((in >> IM_COL32_R_SHIFT) & 0xFF) * s,
((in >> IM_COL32_G_SHIFT) & 0xFF) * s,
((in >> IM_COL32_B_SHIFT) & 0xFF) * s,
((in >> IM_COL32_A_SHIFT) & 0xFF) * s);
}
ImU32 ImGui::ColorConvertFloat4ToU32(const ImVec4& in)
{
ImU32 out;
out = ((ImU32)IM_F32_TO_INT8_SAT(in.x)) << IM_COL32_R_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.y)) << IM_COL32_G_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.z)) << IM_COL32_B_SHIFT;
out |= ((ImU32)IM_F32_TO_INT8_SAT(in.w)) << IM_COL32_A_SHIFT;
return out;
}
// Convert rgb floats ([0-1],[0-1],[0-1]) to hsv floats ([0-1],[0-1],[0-1]), from Foley & van Dam p592
// Optimized http://lolengine.net/blog/2013/01/13/fast-rgb-to-hsv
void ImGui::ColorConvertRGBtoHSV(float r, float g, float b, float& out_h, float& out_s, float& out_v)
{
float K = 0.f;
if (g < b)
{
ImSwap(g, b);
K = -1.f;
}
if (r < g)
{
ImSwap(r, g);
K = -2.f / 6.f - K;
}
const float chroma = r - (g < b ? g : b);
out_h = ImFabs(K + (g - b) / (6.f * chroma + 1e-20f));
out_s = chroma / (r + 1e-20f);
out_v = r;
}
// Convert hsv floats ([0-1],[0-1],[0-1]) to rgb floats ([0-1],[0-1],[0-1]), from Foley & van Dam p593
// also http://en.wikipedia.org/wiki/HSL_and_HSV
void ImGui::ColorConvertHSVtoRGB(float h, float s, float v, float& out_r, float& out_g, float& out_b)
{
if (s == 0.0f)
{
// gray
out_r = out_g = out_b = v;
return;
}
h = ImFmod(h, 1.0f) / (60.0f/360.0f);
int i = (int)h;
float f = h - (float)i;
float p = v * (1.0f - s);
float q = v * (1.0f - s * f);
float t = v * (1.0f - s * (1.0f - f));
switch (i)
{
case 0: out_r = v; out_g = t; out_b = p; break;
case 1: out_r = q; out_g = v; out_b = p; break;
case 2: out_r = p; out_g = v; out_b = t; break;
case 3: out_r = p; out_g = q; out_b = v; break;
case 4: out_r = t; out_g = p; out_b = v; break;
case 5: default: out_r = v; out_g = p; out_b = q; break;
}
}
ImU32 ImGui::GetColorU32(ImGuiCol idx, float alpha_mul)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = style.Colors[idx];
c.w *= style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c);
}
ImU32 ImGui::GetColorU32(const ImVec4& col)
{
ImGuiStyle& style = GImGui->Style;
ImVec4 c = col;
c.w *= style.Alpha;
return ColorConvertFloat4ToU32(c);
}
const ImVec4& ImGui::GetStyleColorVec4(ImGuiCol idx)
{
ImGuiStyle& style = GImGui->Style;
return style.Colors[idx];
}
ImU32 ImGui::GetColorU32(ImU32 col)
{
float style_alpha = GImGui->Style.Alpha;
if (style_alpha >= 1.0f)
return col;
ImU32 a = (col & IM_COL32_A_MASK) >> IM_COL32_A_SHIFT;
a = (ImU32)(a * style_alpha); // We don't need to clamp 0..255 because Style.Alpha is in 0..1 range.
return (col & ~IM_COL32_A_MASK) | (a << IM_COL32_A_SHIFT);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiStorage
// Helper: Key->value storage
//-----------------------------------------------------------------------------
// std::lower_bound but without the bullshit
static ImGuiStorage::Pair* LowerBound(ImVector<ImGuiStorage::Pair>& data, ImGuiID key)
{
ImGuiStorage::Pair* first = data.Data;
ImGuiStorage::Pair* last = data.Data + data.Size;
size_t count = (size_t)(last - first);
while (count > 0)
{
size_t count2 = count >> 1;
ImGuiStorage::Pair* mid = first + count2;
if (mid->key < key)
{
first = ++mid;
count -= count2 + 1;
}
else
{
count = count2;
}
}
return first;
}
// For quicker full rebuild of a storage (instead of an incremental one), you may add all your contents and then sort once.
void ImGuiStorage::BuildSortByKey()
{
struct StaticFunc
{
static int IMGUI_CDECL PairCompareByID(const void* lhs, const void* rhs)
{
// We can't just do a subtraction because qsort uses signed integers and subtracting our ID doesn't play well with that.
if (((const Pair*)lhs)->key > ((const Pair*)rhs)->key) return +1;
if (((const Pair*)lhs)->key < ((const Pair*)rhs)->key) return -1;
return 0;
}
};
if (Data.Size > 1)
ImQsort(Data.Data, (size_t)Data.Size, sizeof(Pair), StaticFunc::PairCompareByID);
}
int ImGuiStorage::GetInt(ImGuiID key, int default_val) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_i;
}
bool ImGuiStorage::GetBool(ImGuiID key, bool default_val) const
{
return GetInt(key, default_val ? 1 : 0) != 0;
}
float ImGuiStorage::GetFloat(ImGuiID key, float default_val) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return default_val;
return it->val_f;
}
void* ImGuiStorage::GetVoidPtr(ImGuiID key) const
{
ImGuiStorage::Pair* it = LowerBound(const_cast<ImVector<ImGuiStorage::Pair>&>(Data), key);
if (it == Data.end() || it->key != key)
return NULL;
return it->val_p;
}
// References are only valid until a new value is added to the storage. Calling a Set***() function or a Get***Ref() function invalidates the pointer.
int* ImGuiStorage::GetIntRef(ImGuiID key, int default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_i;
}
bool* ImGuiStorage::GetBoolRef(ImGuiID key, bool default_val)
{
return (bool*)GetIntRef(key, default_val ? 1 : 0);
}
float* ImGuiStorage::GetFloatRef(ImGuiID key, float default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_f;
}
void** ImGuiStorage::GetVoidPtrRef(ImGuiID key, void* default_val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
it = Data.insert(it, Pair(key, default_val));
return &it->val_p;
}
// FIXME-OPT: Need a way to reuse the result of lower_bound when doing GetInt()/SetInt() - not too bad because it only happens on explicit interaction (maximum one a frame)
void ImGuiStorage::SetInt(ImGuiID key, int val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_i = val;
}
void ImGuiStorage::SetBool(ImGuiID key, bool val)
{
SetInt(key, val ? 1 : 0);
}
void ImGuiStorage::SetFloat(ImGuiID key, float val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_f = val;
}
void ImGuiStorage::SetVoidPtr(ImGuiID key, void* val)
{
ImGuiStorage::Pair* it = LowerBound(Data, key);
if (it == Data.end() || it->key != key)
{
Data.insert(it, Pair(key, val));
return;
}
it->val_p = val;
}
void ImGuiStorage::SetAllInt(int v)
{
for (int i = 0; i < Data.Size; i++)
Data[i].val_i = v;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextFilter
//-----------------------------------------------------------------------------
// Helper: Parse and apply text filters. In format "aaaaa[,bbbb][,ccccc]"
ImGuiTextFilter::ImGuiTextFilter(const char* default_filter)
{
if (default_filter)
{
ImStrncpy(InputBuf, default_filter, IM_ARRAYSIZE(InputBuf));
Build();
}
else
{
InputBuf[0] = 0;
CountGrep = 0;
}
}
bool ImGuiTextFilter::Draw(const char* label, float width)
{
if (width != 0.0f)
ImGui::PushItemWidth(width);
bool value_changed = ImGui::InputText(label, InputBuf, IM_ARRAYSIZE(InputBuf));
if (width != 0.0f)
ImGui::PopItemWidth();
if (value_changed)
Build();
return value_changed;
}
void ImGuiTextFilter::TextRange::split(char separator, ImVector<TextRange>* out) const
{
out->resize(0);
const char* wb = b;
const char* we = wb;
while (we < e)
{
if (*we == separator)
{
out->push_back(TextRange(wb, we));
wb = we + 1;
}
we++;
}
if (wb != we)
out->push_back(TextRange(wb, we));
}
void ImGuiTextFilter::Build()
{
Filters.resize(0);
TextRange input_range(InputBuf, InputBuf+strlen(InputBuf));
input_range.split(',', &Filters);
CountGrep = 0;
for (int i = 0; i != Filters.Size; i++)
{
TextRange& f = Filters[i];
while (f.b < f.e && ImCharIsBlankA(f.b[0]))
f.b++;
while (f.e > f.b && ImCharIsBlankA(f.e[-1]))
f.e--;
if (f.empty())
continue;
if (Filters[i].b[0] != '-')
CountGrep += 1;
}
}
bool ImGuiTextFilter::PassFilter(const char* text, const char* text_end) const
{
if (Filters.empty())
return true;
if (text == NULL)
text = "";
for (int i = 0; i != Filters.Size; i++)
{
const TextRange& f = Filters[i];
if (f.empty())
continue;
if (f.b[0] == '-')
{
// Subtract
if (ImStristr(text, text_end, f.begin()+1, f.end()) != NULL)
return false;
}
else
{
// Grep
if (ImStristr(text, text_end, f.begin(), f.end()) != NULL)
return true;
}
}
// Implicit * grep
if (CountGrep == 0)
return true;
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiTextBuffer
//-----------------------------------------------------------------------------
// On some platform vsnprintf() takes va_list by reference and modifies it.
// va_copy is the 'correct' way to copy a va_list but Visual Studio prior to 2013 doesn't have it.
#ifndef va_copy
#if defined(__GNUC__) || defined(__clang__)
#define va_copy(dest, src) __builtin_va_copy(dest, src)
#else
#define va_copy(dest, src) (dest = src)
#endif
#endif
char ImGuiTextBuffer::EmptyString[1] = { 0 };
void ImGuiTextBuffer::append(const char* str, const char* str_end)
{
int len = str_end ? (int)(str_end - str) : (int)strlen(str);
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
memcpy(&Buf[write_off - 1], str, (size_t)len);
Buf[write_off - 1 + len] = 0;
}
void ImGuiTextBuffer::appendf(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
appendfv(fmt, args);
va_end(args);
}
// Helper: Text buffer for logging/accumulating text
void ImGuiTextBuffer::appendfv(const char* fmt, va_list args)
{
va_list args_copy;
va_copy(args_copy, args);
int len = ImFormatStringV(NULL, 0, fmt, args); // FIXME-OPT: could do a first pass write attempt, likely successful on first pass.
if (len <= 0)
{
va_end(args_copy);
return;
}
// Add zero-terminator the first time
const int write_off = (Buf.Size != 0) ? Buf.Size : 1;
const int needed_sz = write_off + len;
if (write_off + len >= Buf.Capacity)
{
int new_capacity = Buf.Capacity * 2;
Buf.reserve(needed_sz > new_capacity ? needed_sz : new_capacity);
}
Buf.resize(needed_sz);
ImFormatStringV(&Buf[write_off - 1], (size_t)len + 1, fmt, args_copy);
va_end(args_copy);
}
//-----------------------------------------------------------------------------
// [SECTION] ImGuiListClipper
// This is currently not as flexible/powerful as it should be, needs some rework (see TODO)
//-----------------------------------------------------------------------------
static void SetCursorPosYAndSetupDummyPrevLine(float pos_y, float line_height)
{
// Set cursor position and a few other things so that SetScrollHereY() and Columns() can work when seeking cursor.
// FIXME: It is problematic that we have to do that here, because custom/equivalent end-user code would stumble on the same issue.
// The clipper should probably have a 4th step to display the last item in a regular manner.
ImGui::SetCursorPosY(pos_y);
ImGuiWindow* window = ImGui::GetCurrentWindow();
window->DC.CursorPosPrevLine.y = window->DC.CursorPos.y - line_height; // Setting those fields so that SetScrollHereY() can properly function after the end of our clipper usage.
window->DC.PrevLineSize.y = (line_height - GImGui->Style.ItemSpacing.y); // If we end up needing more accurate data (to e.g. use SameLine) we may as well make the clipper have a fourth step to let user process and display the last item in their list.
if (window->DC.ColumnsSet)
window->DC.ColumnsSet->LineMinY = window->DC.CursorPos.y; // Setting this so that cell Y position are set properly
}
// Use case A: Begin() called from constructor with items_height<0, then called again from Sync() in StepNo 1
// Use case B: Begin() called from constructor with items_height>0
// FIXME-LEGACY: Ideally we should remove the Begin/End functions but they are part of the legacy API we still support. This is why some of the code in Step() calling Begin() and reassign some fields, spaghetti style.
void ImGuiListClipper::Begin(int count, float items_height)
{
StartPosY = ImGui::GetCursorPosY();
ItemsHeight = items_height;
ItemsCount = count;
StepNo = 0;
DisplayEnd = DisplayStart = -1;
if (ItemsHeight > 0.0f)
{
ImGui::CalcListClipping(ItemsCount, ItemsHeight, &DisplayStart, &DisplayEnd); // calculate how many to clip/display
if (DisplayStart > 0)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + DisplayStart * ItemsHeight, ItemsHeight); // advance cursor
StepNo = 2;
}
}
void ImGuiListClipper::End()
{
if (ItemsCount < 0)
return;
// In theory here we should assert that ImGui::GetCursorPosY() == StartPosY + DisplayEnd * ItemsHeight, but it feels saner to just seek at the end and not assert/crash the user.
if (ItemsCount < INT_MAX)
SetCursorPosYAndSetupDummyPrevLine(StartPosY + ItemsCount * ItemsHeight, ItemsHeight); // advance cursor
ItemsCount = -1;
StepNo = 3;
}
bool ImGuiListClipper::Step()
{
if (ItemsCount == 0 || ImGui::GetCurrentWindowRead()->SkipItems)
{
ItemsCount = -1;
return false;
}
if (StepNo == 0) // Step 0: the clipper let you process the first element, regardless of it being visible or not, so we can measure the element height.
{
DisplayStart = 0;
DisplayEnd = 1;
StartPosY = ImGui::GetCursorPosY();
StepNo = 1;
return true;
}
if (StepNo == 1) // Step 1: the clipper infer height from first element, calculate the actual range of elements to display, and position the cursor before the first element.
{
if (ItemsCount == 1) { ItemsCount = -1; return false; }
float items_height = ImGui::GetCursorPosY() - StartPosY;
IM_ASSERT(items_height > 0.0f); // If this triggers, it means Item 0 hasn't moved the cursor vertically
Begin(ItemsCount-1, items_height);
DisplayStart++;
DisplayEnd++;
StepNo = 3;
return true;
}
if (StepNo == 2) // Step 2: dummy step only required if an explicit items_height was passed to constructor or Begin() and user still call Step(). Does nothing and switch to Step 3.
{
IM_ASSERT(DisplayStart >= 0 && DisplayEnd >= 0);
StepNo = 3;
return true;
}
if (StepNo == 3) // Step 3: the clipper validate that we have reached the expected Y position (corresponding to element DisplayEnd), advance the cursor to the end of the list and then returns 'false' to end the loop.
End();
return false;
}
//-----------------------------------------------------------------------------
// [SECTION] RENDER HELPERS
// Those (internal) functions are currently quite a legacy mess - their signature and behavior will change.
// Also see imgui_draw.cpp for some more which have been reworked to not rely on ImGui:: state.
//-----------------------------------------------------------------------------
const char* ImGui::FindRenderedTextEnd(const char* text, const char* text_end)
{
const char* text_display_end = text;
if (!text_end)
text_end = (const char*)-1;
while (text_display_end < text_end && *text_display_end != '\0' && (text_display_end[0] != '#' || text_display_end[1] != '#'))
text_display_end++;
return text_display_end;
}
// Internal ImGui functions to render text
// RenderText***() functions calls ImDrawList::AddText() calls ImBitmapFont::RenderText()
void ImGui::RenderText(ImVec2 pos, const char* text, const char* text_end, bool hide_text_after_hash)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// Hide anything after a '##' string
const char* text_display_end;
if (hide_text_after_hash)
{
text_display_end = FindRenderedTextEnd(text, text_end);
}
else
{
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
text_display_end = text_end;
}
if (text != text_display_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_display_end);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_display_end);
}
}
void ImGui::RenderTextWrapped(ImVec2 pos, const char* text, const char* text_end, float wrap_width)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = text + strlen(text); // FIXME-OPT
if (text != text_end)
{
window->DrawList->AddText(g.Font, g.FontSize, pos, GetColorU32(ImGuiCol_Text), text, text_end, wrap_width);
if (g.LogEnabled)
LogRenderedText(&pos, text, text_end);
}
}
// Default clip_rect uses (pos_min,pos_max)
// Handle clipping on CPU immediately (vs typically let the GPU clip the triangles that are overlapping the clipping rectangle edges)
void ImGui::RenderTextClippedEx(ImDrawList* draw_list, const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_display_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Perform CPU side clipping for single clipped element to avoid using scissor state
ImVec2 pos = pos_min;
const ImVec2 text_size = text_size_if_known ? *text_size_if_known : CalcTextSize(text, text_display_end, false, 0.0f);
const ImVec2* clip_min = clip_rect ? &clip_rect->Min : &pos_min;
const ImVec2* clip_max = clip_rect ? &clip_rect->Max : &pos_max;
bool need_clipping = (pos.x + text_size.x >= clip_max->x) || (pos.y + text_size.y >= clip_max->y);
if (clip_rect) // If we had no explicit clipping rectangle then pos==clip_min
need_clipping |= (pos.x < clip_min->x) || (pos.y < clip_min->y);
// Align whole block. We should defer that to the better rendering function when we'll have support for individual line alignment.
if (align.x > 0.0f) pos.x = ImMax(pos.x, pos.x + (pos_max.x - pos.x - text_size.x) * align.x);
if (align.y > 0.0f) pos.y = ImMax(pos.y, pos.y + (pos_max.y - pos.y - text_size.y) * align.y);
// Render
if (need_clipping)
{
ImVec4 fine_clip_rect(clip_min->x, clip_min->y, clip_max->x, clip_max->y);
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, &fine_clip_rect);
}
else
{
draw_list->AddText(NULL, 0.0f, pos, GetColorU32(ImGuiCol_Text), text, text_display_end, 0.0f, NULL);
}
}
void ImGui::RenderTextClipped(const ImVec2& pos_min, const ImVec2& pos_max, const char* text, const char* text_end, const ImVec2* text_size_if_known, const ImVec2& align, const ImRect* clip_rect)
{
// Hide anything after a '##' string
const char* text_display_end = FindRenderedTextEnd(text, text_end);
const int text_len = (int)(text_display_end - text);
if (text_len == 0)
return;
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
RenderTextClippedEx(window->DrawList, pos_min, pos_max, text, text_display_end, text_size_if_known, align, clip_rect);
if (g.LogEnabled)
LogRenderedText(&pos_min, text, text_display_end);
}
// Render a rectangle shaped with optional rounding and borders
void ImGui::RenderFrame(ImVec2 p_min, ImVec2 p_max, ImU32 fill_col, bool border, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(p_min, p_max, fill_col, rounding);
const float border_size = g.Style.FrameBorderSize;
if (border && border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
void ImGui::RenderFrameBorder(ImVec2 p_min, ImVec2 p_max, float rounding)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const float border_size = g.Style.FrameBorderSize;
if (border_size > 0.0f)
{
window->DrawList->AddRect(p_min+ImVec2(1,1), p_max+ImVec2(1,1), GetColorU32(ImGuiCol_BorderShadow), rounding, ImDrawCornerFlags_All, border_size);
window->DrawList->AddRect(p_min, p_max, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
}
}
// Render an arrow aimed to be aligned with text (p_min is a position in the same space text would be positioned). To e.g. denote expanded/collapsed state
void ImGui::RenderArrow(ImVec2 p_min, ImGuiDir dir, float scale)
{
ImGuiContext& g = *GImGui;
const float h = g.FontSize * 1.00f;
float r = h * 0.40f * scale;
ImVec2 center = p_min + ImVec2(h * 0.50f, h * 0.50f * scale);
ImVec2 a, b, c;
switch (dir)
{
case ImGuiDir_Up:
case ImGuiDir_Down:
if (dir == ImGuiDir_Up) r = -r;
a = ImVec2(+0.000f,+0.750f) * r;
b = ImVec2(-0.866f,-0.750f) * r;
c = ImVec2(+0.866f,-0.750f) * r;
break;
case ImGuiDir_Left:
case ImGuiDir_Right:
if (dir == ImGuiDir_Left) r = -r;
a = ImVec2(+0.750f,+0.000f) * r;
b = ImVec2(-0.750f,+0.866f) * r;
c = ImVec2(-0.750f,-0.866f) * r;
break;
case ImGuiDir_None:
case ImGuiDir_COUNT:
IM_ASSERT(0);
break;
}
g.CurrentWindow->DrawList->AddTriangleFilled(center + a, center + b, center + c, GetColorU32(ImGuiCol_Text));
}
void ImGui::RenderBullet(ImVec2 pos)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddCircleFilled(pos, g.FontSize*0.20f, GetColorU32(ImGuiCol_Text), 8);
}
void ImGui::RenderCheckMark(ImVec2 pos, ImU32 col, float sz)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
float thickness = ImMax(sz / 5.0f, 1.0f);
sz -= thickness*0.5f;
pos += ImVec2(thickness*0.25f, thickness*0.25f);
float third = sz / 3.0f;
float bx = pos.x + third;
float by = pos.y + sz - third*0.5f;
window->DrawList->PathLineTo(ImVec2(bx - third, by - third));
window->DrawList->PathLineTo(ImVec2(bx, by));
window->DrawList->PathLineTo(ImVec2(bx + third*2, by - third*2));
window->DrawList->PathStroke(col, false, thickness);
}
void ImGui::RenderNavHighlight(const ImRect& bb, ImGuiID id, ImGuiNavHighlightFlags flags)
{
ImGuiContext& g = *GImGui;
if (id != g.NavId)
return;
if (g.NavDisableHighlight && !(flags & ImGuiNavHighlightFlags_AlwaysDraw))
return;
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.NavHideHighlightOneFrame)
return;
float rounding = (flags & ImGuiNavHighlightFlags_NoRounding) ? 0.0f : g.Style.FrameRounding;
ImRect display_rect = bb;
display_rect.ClipWith(window->ClipRect);
if (flags & ImGuiNavHighlightFlags_TypeDefault)
{
const float THICKNESS = 2.0f;
const float DISTANCE = 3.0f + THICKNESS * 0.5f;
display_rect.Expand(ImVec2(DISTANCE,DISTANCE));
bool fully_visible = window->ClipRect.Contains(display_rect);
if (!fully_visible)
window->DrawList->PushClipRect(display_rect.Min, display_rect.Max);
window->DrawList->AddRect(display_rect.Min + ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), display_rect.Max - ImVec2(THICKNESS*0.5f,THICKNESS*0.5f), GetColorU32(ImGuiCol_NavHighlight), rounding, ImDrawCornerFlags_All, THICKNESS);
if (!fully_visible)
window->DrawList->PopClipRect();
}
if (flags & ImGuiNavHighlightFlags_TypeThin)
{
window->DrawList->AddRect(display_rect.Min, display_rect.Max, GetColorU32(ImGuiCol_NavHighlight), rounding, ~0, 1.0f);
}
}
//-----------------------------------------------------------------------------
// [SECTION] MAIN CODE (most of the code! lots of stuff, needs tidying up!)
//-----------------------------------------------------------------------------
// ImGuiWindow is mostly a dumb struct. It merely has a constructor and a few helper methods
ImGuiWindow::ImGuiWindow(ImGuiContext* context, const char* name)
: DrawListInst(&context->DrawListSharedData)
{
Name = ImStrdup(name);
ID = ImHashStr(name, 0);
IDStack.push_back(ID);
Flags = FlagsPreviousFrame = ImGuiWindowFlags_None;
Viewport = NULL;
ViewportId = 0;
ViewportAllowPlatformMonitorExtend = -1;
ViewportPos = ImVec2(FLT_MAX, FLT_MAX);
Pos = ImVec2(0.0f, 0.0f);
Size = SizeFull = ImVec2(0.0f, 0.0f);
SizeContents = SizeContentsExplicit = ImVec2(0.0f, 0.0f);
WindowPadding = ImVec2(0.0f, 0.0f);
WindowRounding = 0.0f;
WindowBorderSize = 0.0f;
NameBufLen = (int)strlen(name) + 1;
MoveId = GetID("#MOVE");
ChildId = 0;
Scroll = ImVec2(0.0f, 0.0f);
ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
ScrollTargetCenterRatio = ImVec2(0.5f, 0.5f);
ScrollbarSizes = ImVec2(0.0f, 0.0f);
ScrollbarX = ScrollbarY = false;
ViewportOwned = false;
Active = WasActive = false;
WriteAccessed = false;
Collapsed = false;
WantCollapseToggle = false;
SkipItems = false;
Appearing = false;
Hidden = false;
HasCloseButton = false;
ResizeBorderHeld = -1;
BeginCount = 0;
BeginOrderWithinParent = -1;
BeginOrderWithinContext = -1;
PopupId = 0;
AutoFitFramesX = AutoFitFramesY = -1;
AutoFitOnlyGrows = false;
AutoFitChildAxises = 0x00;
AutoPosLastDirection = ImGuiDir_None;
HiddenFramesRegular = HiddenFramesForResize = 0;
SetWindowPosAllowFlags = SetWindowSizeAllowFlags = SetWindowCollapsedAllowFlags = SetWindowDockAllowFlags = ImGuiCond_Always | ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing;
SetWindowPosVal = SetWindowPosPivot = ImVec2(FLT_MAX, FLT_MAX);
LastFrameActive = -1;
ItemWidthDefault = 0.0f;
FontWindowScale = FontDpiScale = 1.0f;
SettingsIdx = -1;
DrawList = &DrawListInst;
DrawList->_OwnerName = Name;
ParentWindow = NULL;
RootWindow = NULL;
RootWindowDockStop = NULL;
RootWindowForTitleBarHighlight = NULL;
RootWindowForNav = NULL;
NavLastIds[0] = NavLastIds[1] = 0;
NavRectRel[0] = NavRectRel[1] = ImRect();
NavLastChildNavWindow = NULL;
FocusIdxAllCounter = FocusIdxTabCounter = -1;
FocusIdxAllRequestCurrent = FocusIdxTabRequestCurrent = INT_MAX;
FocusIdxAllRequestNext = FocusIdxTabRequestNext = INT_MAX;
DockNode = DockNodeAsHost = NULL;
DockId = 0;
DockTabItemStatusFlags = 0;
DockOrder = -1;
DockIsActive = DockTabIsVisible = DockTabWantClose = false;
}
ImGuiWindow::~ImGuiWindow()
{
IM_ASSERT(DrawList == &DrawListInst);
IM_DELETE(Name);
for (int i = 0; i != ColumnsStorage.Size; i++)
ColumnsStorage[i].~ImGuiColumnsSet();
}
ImGuiID ImGuiWindow::GetID(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashStr(str, str_end ? (str_end - str) : 0, seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetID(const void* ptr)
{
ImGuiID seed = IDStack.back();
ImGuiID id = ImHashData(&ptr, sizeof(void*), seed);
ImGui::KeepAliveID(id);
return id;
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const char* str, const char* str_end)
{
ImGuiID seed = IDStack.back();
return ImHashStr(str, str_end ? (str_end - str) : 0, seed);
}
ImGuiID ImGuiWindow::GetIDNoKeepAlive(const void* ptr)
{
ImGuiID seed = IDStack.back();
return ImHashData(&ptr, sizeof(void*), seed);
}
// This is only used in rare/specific situations to manufacture an ID out of nowhere.
ImGuiID ImGuiWindow::GetIDFromRectangle(const ImRect& r_abs)
{
ImGuiID seed = IDStack.back();
const int r_rel[4] = { (int)(r_abs.Min.x - Pos.x), (int)(r_abs.Min.y - Pos.y), (int)(r_abs.Max.x - Pos.x), (int)(r_abs.Max.y - Pos.y) };
ImGuiID id = ImHashData(&r_rel, sizeof(r_rel), seed);
ImGui::KeepAliveID(id);
return id;
}
static void SetCurrentWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.CurrentWindow = window;
if (window)
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
void ImGui::SetNavID(ImGuiID id, int nav_layer)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindow);
IM_ASSERT(nav_layer == 0 || nav_layer == 1);
g.NavId = id;
g.NavWindow->NavLastIds[nav_layer] = id;
}
void ImGui::SetNavIDWithRectRel(ImGuiID id, int nav_layer, const ImRect& rect_rel)
{
ImGuiContext& g = *GImGui;
SetNavID(id, nav_layer);
g.NavWindow->NavRectRel[nav_layer] = rect_rel;
g.NavMousePosDirty = true;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
void ImGui::SetActiveID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
g.ActiveIdIsJustActivated = (g.ActiveId != id);
if (g.ActiveIdIsJustActivated)
{
g.ActiveIdTimer = 0.0f;
g.ActiveIdHasBeenPressed = false;
g.ActiveIdHasBeenEdited = false;
if (id != 0)
{
g.LastActiveId = id;
g.LastActiveIdTimer = 0.0f;
}
}
g.ActiveId = id;
g.ActiveIdAllowNavDirFlags = 0;
g.ActiveIdBlockNavInputFlags = 0;
g.ActiveIdAllowOverlap = false;
g.ActiveIdWindow = window;
if (id)
{
g.ActiveIdIsAlive = id;
g.ActiveIdSource = (g.NavActivateId == id || g.NavInputId == id || g.NavJustTabbedId == id || g.NavJustMovedToId == id) ? ImGuiInputSource_Nav : ImGuiInputSource_Mouse;
}
}
// FIXME-NAV: The existence of SetNavID/SetNavIDWithRectRel/SetFocusID is incredibly messy and confusing and needs some explanation or refactoring.
void ImGui::SetFocusID(ImGuiID id, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
// Assume that SetFocusID() is called in the context where its NavLayer is the current layer, which is the case everywhere we call it.
const ImGuiNavLayer nav_layer = window->DC.NavLayerCurrent;
if (g.NavWindow != window)
g.NavInitRequest = false;
g.NavId = id;
g.NavWindow = window;
g.NavLayer = nav_layer;
window->NavLastIds[nav_layer] = id;
if (window->DC.LastItemId == id)
window->NavRectRel[nav_layer] = ImRect(window->DC.LastItemRect.Min - window->Pos, window->DC.LastItemRect.Max - window->Pos);
if (g.ActiveIdSource == ImGuiInputSource_Nav)
g.NavDisableMouseHover = true;
else
g.NavDisableHighlight = true;
}
void ImGui::ClearActiveID()
{
SetActiveID(0, NULL);
}
void ImGui::SetHoveredID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.HoveredId = id;
g.HoveredIdAllowOverlap = false;
if (id != 0 && g.HoveredIdPreviousFrame != id)
g.HoveredIdTimer = g.HoveredIdNotActiveTimer = 0.0f;
}
ImGuiID ImGui::GetHoveredID()
{
ImGuiContext& g = *GImGui;
return g.HoveredId ? g.HoveredId : g.HoveredIdPreviousFrame;
}
void ImGui::KeepAliveID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.ActiveId == id)
g.ActiveIdIsAlive = id;
if (g.ActiveIdPreviousFrame == id)
g.ActiveIdPreviousFrameIsAlive = true;
}
void ImGui::MarkItemEdited(ImGuiID id)
{
// This marking is solely to be able to provide info for IsItemDeactivatedAfterEdit().
// ActiveId might have been released by the time we call this (as in the typical press/release button behavior) but still need need to fill the data.
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == id || g.ActiveId == 0 || g.DragDropActive);
IM_UNUSED(id); // Avoid unused variable warnings when asserts are compiled out.
//IM_ASSERT(g.CurrentWindow->DC.LastItemId == id);
g.ActiveIdHasBeenEdited = true;
g.CurrentWindow->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_Edited;
}
static inline bool IsWindowContentHoverable(ImGuiWindow* window, ImGuiHoveredFlags flags)
{
// An active popup disable hovering on other windows (apart from its own children)
// FIXME-OPT: This could be cached/stored within the window.
ImGuiContext& g = *GImGui;
if (g.NavWindow)
if (ImGuiWindow* focused_root_window = g.NavWindow->RootWindow)
if (focused_root_window->WasActive && focused_root_window != window->RootWindow)
{
// For the purpose of those flags we differentiate "standard popup" from "modal popup"
// NB: The order of those two tests is important because Modal windows are also Popups.
if (focused_root_window->Flags & ImGuiWindowFlags_Modal)
return false;
if ((focused_root_window->Flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiHoveredFlags_AllowWhenBlockedByPopup))
return false;
}
// Filter by viewport
if (window->Viewport != g.MouseViewport)
if (g.MovingWindow == NULL || window->RootWindow != g.MovingWindow->RootWindow)
return false;
return true;
}
// Advance cursor given item size for layout.
void ImGui::ItemSize(const ImVec2& size, float text_offset_y)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (window->SkipItems)
return;
// Always align ourselves on pixel boundaries
const float line_height = ImMax(window->DC.CurrentLineSize.y, size.y);
const float text_base_offset = ImMax(window->DC.CurrentLineTextBaseOffset, text_offset_y);
//if (g.IO.KeyAlt) window->DrawList->AddRect(window->DC.CursorPos, window->DC.CursorPos + ImVec2(size.x, line_height), IM_COL32(255,0,0,200)); // [DEBUG]
window->DC.CursorPosPrevLine = ImVec2(window->DC.CursorPos.x + size.x, window->DC.CursorPos.y);
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = (float)(int)(window->DC.CursorPos.y + line_height + g.Style.ItemSpacing.y);
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPosPrevLine.x);
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y - g.Style.ItemSpacing.y);
//if (g.IO.KeyAlt) window->DrawList->AddCircle(window->DC.CursorMaxPos, 3.0f, IM_COL32(255,0,0,255), 4); // [DEBUG]
window->DC.PrevLineSize.y = line_height;
window->DC.PrevLineTextBaseOffset = text_base_offset;
window->DC.CurrentLineSize.y = window->DC.CurrentLineTextBaseOffset = 0.0f;
// Horizontal layout mode
if (window->DC.LayoutType == ImGuiLayoutType_Horizontal)
SameLine();
}
void ImGui::ItemSize(const ImRect& bb, float text_offset_y)
{
ItemSize(bb.GetSize(), text_offset_y);
}
// Declare item bounding box for clipping and interaction.
// Note that the size can be different than the one provided to ItemSize(). Typically, widgets that spread over available surface
// declare their minimum size requirement to ItemSize() and then use a larger region for drawing/interaction, which is passed to ItemAdd().
bool ImGui::ItemAdd(const ImRect& bb, ImGuiID id, const ImRect* nav_bb_arg)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (id != 0)
{
// Navigation processing runs prior to clipping early-out
// (a) So that NavInitRequest can be honored, for newly opened windows to select a default widget
// (b) So that we can scroll up/down past clipped items. This adds a small O(N) cost to regular navigation requests unfortunately, but it is still limited to one window.
// it may not scale very well for windows with ten of thousands of item, but at least NavMoveRequest is only set on user interaction, aka maximum once a frame.
// We could early out with "if (is_clipped && !g.NavInitRequest) return false;" but when we wouldn't be able to reach unclipped widgets. This would work if user had explicit scrolling control (e.g. mapped on a stick)
window->DC.NavLayerActiveMaskNext |= window->DC.NavLayerCurrentMask;
if (g.NavId == id || g.NavAnyRequest)
if (g.NavWindow->RootWindowForNav == window->RootWindowForNav)
if (window == g.NavWindow || ((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened))
NavProcessItem(window, nav_bb_arg ? *nav_bb_arg : bb, id);
}
window->DC.LastItemId = id;
window->DC.LastItemRect = bb;
window->DC.LastItemStatusFlags = ImGuiItemStatusFlags_None;
#ifdef IMGUI_ENABLE_TEST_ENGINE
if (id != 0)
ImGuiTestEngineHook_ItemAdd(&g, nav_bb_arg ? *nav_bb_arg : bb, id);
#endif
// Clipping test
const bool is_clipped = IsClippedEx(bb, id, false);
if (is_clipped)
return false;
//if (g.IO.KeyAlt) window->DrawList->AddRect(bb.Min, bb.Max, IM_COL32(255,255,0,120)); // [DEBUG]
// We need to calculate this now to take account of the current clipping rectangle (as items like Selectable may change them)
if (IsMouseHoveringRect(bb.Min, bb.Max))
window->DC.LastItemStatusFlags |= ImGuiItemStatusFlags_HoveredRect;
return true;
}
// This is roughly matching the behavior of internal-facing ItemHoverable()
// - we allow hovering to be true when ActiveId==window->MoveID, so that clicking on non-interactive items such as a Text() item still returns true with IsItemHovered()
// - this should work even for non-interactive items that have no ID, so we cannot use LastItemId
bool ImGui::IsItemHovered(ImGuiHoveredFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavDisableMouseHover && !g.NavDisableHighlight)
return IsItemFocused();
// Test for bounding box overlap, as updated as ItemAdd()
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
IM_ASSERT((flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows)) == 0); // Flags not supported by this function
// Test if we are hovering the right window (our window could be behind another window)
// [2017/10/16] Reverted commit 344d48be3 and testing RootWindow instead. I believe it is correct to NOT test for RootWindow but this leaves us unable to use IsItemHovered() after EndChild() itself.
// Until a solution is found I believe reverting to the test from 2017/09/27 is safe since this was the test that has been running for a long while.
//if (g.HoveredWindow != window)
// return false;
if (g.HoveredRootWindow != window->RootWindow && !(flags & ImGuiHoveredFlags_AllowWhenOverlapped))
return false;
// Test if another item is active (e.g. being dragged)
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && g.ActiveId != window->DC.LastItemId && !g.ActiveIdAllowOverlap && g.ActiveId != window->MoveId)
return false;
// Test if interactions on this window are blocked by an active popup or modal
if (!IsWindowContentHoverable(window, flags))
return false;
// Test if the item is disabled
if ((window->DC.ItemFlags & ImGuiItemFlags_Disabled) && !(flags & ImGuiHoveredFlags_AllowWhenDisabled))
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if ((window->DC.LastItemId == window->ID || window->DC.LastItemId == window->MoveId) && window->WriteAccessed)
return false;
return true;
}
// Internal facing ItemHoverable() used when submitting widgets. Differs slightly from IsItemHovered().
bool ImGui::ItemHoverable(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (g.HoveredId != 0 && g.HoveredId != id && !g.HoveredIdAllowOverlap)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindow != window)
return false;
if (g.ActiveId != 0 && g.ActiveId != id && !g.ActiveIdAllowOverlap)
return false;
if (!IsMouseHoveringRect(bb.Min, bb.Max))
return false;
if (g.NavDisableMouseHover || !IsWindowContentHoverable(window, ImGuiHoveredFlags_None))
return false;
if (window->DC.ItemFlags & ImGuiItemFlags_Disabled)
return false;
SetHoveredID(id);
return true;
}
bool ImGui::IsClippedEx(const ImRect& bb, ImGuiID id, bool clip_even_when_logged)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!bb.Overlaps(window->ClipRect))
if (id == 0 || id != g.ActiveId)
if (clip_even_when_logged || !g.LogEnabled)
return true;
return false;
}
bool ImGui::FocusableItemRegister(ImGuiWindow* window, ImGuiID id, bool tab_stop)
{
ImGuiContext& g = *GImGui;
const bool is_tab_stop = (window->DC.ItemFlags & (ImGuiItemFlags_NoTabStop | ImGuiItemFlags_Disabled)) == 0;
window->FocusIdxAllCounter++;
if (is_tab_stop)
window->FocusIdxTabCounter++;
// Process keyboard input at this point: TAB/Shift-TAB to tab out of the currently focused item.
// Note that we can always TAB out of a widget that doesn't allow tabbing in.
if (tab_stop && (g.ActiveId == id) && window->FocusIdxAllRequestNext == INT_MAX && window->FocusIdxTabRequestNext == INT_MAX && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab))
window->FocusIdxTabRequestNext = window->FocusIdxTabCounter + (g.IO.KeyShift ? (is_tab_stop ? -1 : 0) : +1); // Modulo on index will be applied at the end of frame once we've got the total counter of items.
if (window->FocusIdxAllCounter == window->FocusIdxAllRequestCurrent)
return true;
if (is_tab_stop && window->FocusIdxTabCounter == window->FocusIdxTabRequestCurrent)
{
g.NavJustTabbedId = id;
return true;
}
return false;
}
void ImGui::FocusableItemUnregister(ImGuiWindow* window)
{
window->FocusIdxAllCounter--;
window->FocusIdxTabCounter--;
}
ImVec2 ImGui::CalcItemSize(ImVec2 size, float default_x, float default_y)
{
ImGuiContext& g = *GImGui;
ImVec2 content_max;
if (size.x < 0.0f || size.y < 0.0f)
content_max = g.CurrentWindow->Pos + GetContentRegionMax();
if (size.x <= 0.0f)
size.x = (size.x == 0.0f) ? default_x : ImMax(content_max.x - g.CurrentWindow->DC.CursorPos.x, 4.0f) + size.x;
if (size.y <= 0.0f)
size.y = (size.y == 0.0f) ? default_y : ImMax(content_max.y - g.CurrentWindow->DC.CursorPos.y, 4.0f) + size.y;
return size;
}
float ImGui::CalcWrapWidthForPos(const ImVec2& pos, float wrap_pos_x)
{
if (wrap_pos_x < 0.0f)
return 0.0f;
ImGuiWindow* window = GetCurrentWindowRead();
if (wrap_pos_x == 0.0f)
wrap_pos_x = GetContentRegionMax().x + window->Pos.x;
else if (wrap_pos_x > 0.0f)
wrap_pos_x += window->Pos.x - window->Scroll.x; // wrap_pos_x is provided is window local space
return ImMax(wrap_pos_x - pos.x, 1.0f);
}
void* ImGui::MemAlloc(size_t size)
{
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations++;
return GImAllocatorAllocFunc(size, GImAllocatorUserData);
}
void ImGui::MemFree(void* ptr)
{
if (ptr)
if (ImGuiContext* ctx = GImGui)
ctx->IO.MetricsActiveAllocations--;
return GImAllocatorFreeFunc(ptr, GImAllocatorUserData);
}
const char* ImGui::GetClipboardText()
{
return GImGui->IO.GetClipboardTextFn ? GImGui->IO.GetClipboardTextFn(GImGui->IO.ClipboardUserData) : "";
}
void ImGui::SetClipboardText(const char* text)
{
if (GImGui->IO.SetClipboardTextFn)
GImGui->IO.SetClipboardTextFn(GImGui->IO.ClipboardUserData, text);
}
const char* ImGui::GetVersion()
{
return IMGUI_VERSION;
}
// Internal state access - if you want to share ImGui state between modules (e.g. DLL) or allocate it yourself
// Note that we still point to some static data and members (such as GFontAtlas), so the state instance you end up using will point to the static data within its module
ImGuiContext* ImGui::GetCurrentContext()
{
return GImGui;
}
void ImGui::SetCurrentContext(ImGuiContext* ctx)
{
#ifdef IMGUI_SET_CURRENT_CONTEXT_FUNC
IMGUI_SET_CURRENT_CONTEXT_FUNC(ctx); // For custom thread-based hackery you may want to have control over this.
#else
GImGui = ctx;
#endif
}
// Helper function to verify that the type sizes are matching between the calling file's compilation unit and imgui.cpp's compilation unit
// If the user has inconsistent compilation settings, imgui configuration #define, packing pragma, etc. you may see different structures from what imgui.cpp sees which is highly problematic.
bool ImGui::DebugCheckVersionAndDataLayout(const char* version, size_t sz_io, size_t sz_style, size_t sz_vec2, size_t sz_vec4, size_t sz_vert)
{
bool error = false;
if (strcmp(version, IMGUI_VERSION)!=0) { error = true; IM_ASSERT(strcmp(version,IMGUI_VERSION)==0 && "Mismatched version string!"); }
if (sz_io != sizeof(ImGuiIO)) { error = true; IM_ASSERT(sz_io == sizeof(ImGuiIO) && "Mismatched struct layout!"); }
if (sz_style != sizeof(ImGuiStyle)) { error = true; IM_ASSERT(sz_style == sizeof(ImGuiStyle) && "Mismatched struct layout!"); }
if (sz_vec2 != sizeof(ImVec2)) { error = true; IM_ASSERT(sz_vec2 == sizeof(ImVec2) && "Mismatched struct layout!"); }
if (sz_vec4 != sizeof(ImVec4)) { error = true; IM_ASSERT(sz_vec4 == sizeof(ImVec4) && "Mismatched struct layout!"); }
if (sz_vert != sizeof(ImDrawVert)) { error = true; IM_ASSERT(sz_vert == sizeof(ImDrawVert) && "Mismatched struct layout!"); }
return !error;
}
void ImGui::SetAllocatorFunctions(void* (*alloc_func)(size_t sz, void* user_data), void (*free_func)(void* ptr, void* user_data), void* user_data)
{
GImAllocatorAllocFunc = alloc_func;
GImAllocatorFreeFunc = free_func;
GImAllocatorUserData = user_data;
}
ImGuiContext* ImGui::CreateContext(ImFontAtlas* shared_font_atlas)
{
ImGuiContext* ctx = IM_NEW(ImGuiContext)(shared_font_atlas);
if (GImGui == NULL)
SetCurrentContext(ctx);
Initialize(ctx);
return ctx;
}
void ImGui::DestroyContext(ImGuiContext* ctx)
{
if (ctx == NULL)
ctx = GImGui;
Shutdown(ctx);
if (GImGui == ctx)
SetCurrentContext(NULL);
IM_DELETE(ctx);
}
ImGuiIO& ImGui::GetIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->IO;
}
ImGuiPlatformIO& ImGui::GetPlatformIO()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->PlatformIO;
}
ImGuiStyle& ImGui::GetStyle()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
return GImGui->Style;
}
// Same value as passed to the old io.RenderDrawListsFn function. Valid after Render() and until the next call to NewFrame()
ImDrawData* ImGui::GetDrawData()
{
ImGuiContext& g = *GImGui;
return g.Viewports[0]->DrawDataP.Valid ? &g.Viewports[0]->DrawDataP : NULL;
}
double ImGui::GetTime()
{
return GImGui->Time;
}
int ImGui::GetFrameCount()
{
return GImGui->FrameCount;
}
ImDrawList* ImGui::GetOverlayDrawList(ImGuiViewport* viewport_public)
{
// Create the draw list on demand, because it is not frequently used for all viewports
ImGuiContext& g = *GImGui;
ImGuiViewportP* viewport = (ImGuiViewportP*)viewport_public;
if (viewport->OverlayDrawList == NULL)
{
viewport->OverlayDrawList = IM_NEW(ImDrawList)(&g.DrawListSharedData);
viewport->OverlayDrawList->_OwnerName = "##Overlay";
}
// Our ImDrawList system requires that there is always a command
if (viewport->LastFrameOverlayDrawList != g.FrameCount)
{
viewport->OverlayDrawList->Clear();
viewport->OverlayDrawList->PushTextureID(g.IO.Fonts->TexID);
viewport->OverlayDrawList->PushClipRect(viewport->Pos, viewport->Pos + viewport->Size, false);
viewport->OverlayDrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
viewport->LastFrameOverlayDrawList = g.FrameCount;
}
return viewport->OverlayDrawList;
}
ImDrawList* ImGui::GetOverlayDrawList()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return GetOverlayDrawList(window->Viewport);
}
ImDrawListSharedData* ImGui::GetDrawListSharedData()
{
return &GImGui->DrawListSharedData;
}
void ImGui::StartMouseMovingWindow(ImGuiWindow* window)
{
// Set ActiveId even if the _NoMove flag is set. Without it, dragging away from a window with _NoMove would activate hover on other windows.
// We _also_ call this when clicking in a window empty space when io.ConfigWindowsMoveFromTitleBarOnly is set, but clear g.MovingWindow afterward.
// This is because we want ActiveId to be set even when the window is not permitted to move.
ImGuiContext& g = *GImGui;
FocusWindow(window);
SetActiveID(window->MoveId, window);
g.NavDisableHighlight = true;
g.ActiveIdClickOffset = g.IO.MousePos - window->RootWindow->Pos;
bool can_move_window = true;
if ((window->Flags & ImGuiWindowFlags_NoMove) || (window->RootWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (ImGuiDockNode* node = window->DockNodeAsHost)
if (node->VisibleWindow && (node->VisibleWindow->Flags & ImGuiWindowFlags_NoMove))
can_move_window = false;
if (can_move_window)
g.MovingWindow = window;
}
// Handle mouse moving window
// Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
void ImGui::UpdateMouseMovingWindowNewFrame()
{
ImGuiContext& g = *GImGui;
if (g.MovingWindow != NULL)
{
// We actually want to move the root window. g.MovingWindow == window we clicked on (could be a child window).
// We track it to preserve Focus and so that generally ActiveIdWindow == MovingWindow and ActiveId == MovingWindow->MoveId for consistency.
KeepAliveID(g.ActiveId);
IM_ASSERT(g.MovingWindow && g.MovingWindow->RootWindow);
ImGuiWindow* moving_window = g.MovingWindow->RootWindow;
if (g.IO.MouseDown[0] && IsMousePosValid(&g.IO.MousePos))
{
ImVec2 pos = g.IO.MousePos - g.ActiveIdClickOffset;
if (moving_window->Pos.x != pos.x || moving_window->Pos.y != pos.y)
{
MarkIniSettingsDirty(moving_window);
SetWindowPos(moving_window, pos, ImGuiCond_Always);
if (moving_window->ViewportOwned) // Synchronize viewport immediately because some overlays may relies on clipping rectangle before we Begin() into the window.
moving_window->Viewport->Pos = pos;
}
FocusWindow(g.MovingWindow);
}
else
{
// Try to merge the window back into the main viewport.
// This works because MouseViewport should be != MovingWindow->Viewport on release (as per code in UpdateViewports)
if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)
UpdateTryMergeWindowIntoHostViewport(moving_window, g.MouseViewport);
// Restore the mouse viewport so that we don't hover the viewport _under_ the moved window during the frame we released the mouse button.
if (!IsDragDropPayloadBeingAccepted())
g.MouseViewport = moving_window->Viewport;
// Clear the NoInput window flag set by the Viewport system
moving_window->Viewport->Flags &= ~ImGuiViewportFlags_NoInputs;
ClearActiveID();
g.MovingWindow = NULL;
}
}
else
{
// When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order to prevent hovering others.
if (g.ActiveIdWindow && g.ActiveIdWindow->MoveId == g.ActiveId)
{
KeepAliveID(g.ActiveId);
if (!g.IO.MouseDown[0])
ClearActiveID();
}
}
}
// Initiate moving window, handle left-click and right-click focus
void ImGui::UpdateMouseMovingWindowEndFrame()
{
// Initiate moving window
ImGuiContext& g = *GImGui;
if (g.ActiveId != 0 || g.HoveredId != 0)
return;
// Unless we just made a window/popup appear
if (g.NavWindow && g.NavWindow->Appearing)
return;
// Click to focus window and start moving (after we're done with all our widgets)
if (g.IO.MouseClicked[0])
{
if (g.HoveredRootWindow != NULL)
{
StartMouseMovingWindow(g.HoveredWindow);
if (g.IO.ConfigWindowsMoveFromTitleBarOnly && (!(g.HoveredRootWindow->Flags & ImGuiWindowFlags_NoTitleBar) || g.HoveredWindow->RootWindowDockStop->DockIsActive))
if (!g.HoveredRootWindow->TitleBarRect().Contains(g.IO.MouseClickedPos[0]))
g.MovingWindow = NULL;
}
else if (g.NavWindow != NULL && GetFrontMostPopupModal() == NULL)
{
// Clicking on void disable focus
FocusWindow(NULL);
}
}
// With right mouse button we close popups without changing focus
// (The left mouse button path calls FocusWindow which will lead NewFrame->ClosePopupsOverWindow to trigger)
if (g.IO.MouseClicked[1])
{
// Find the top-most window between HoveredWindow and the front most Modal Window.
// This is where we can trim the popup stack.
ImGuiWindow* modal = GetFrontMostPopupModal();
bool hovered_window_above_modal = false;
if (modal == NULL)
hovered_window_above_modal = true;
for (int i = g.Windows.Size - 1; i >= 0 && hovered_window_above_modal == false; i--)
{
ImGuiWindow* window = g.Windows[i];
if (window == modal)
break;
if (window == g.HoveredWindow)
hovered_window_above_modal = true;
}
ClosePopupsOverWindow(hovered_window_above_modal ? g.HoveredWindow : modal);
}
}
static void TranslateWindow(ImGuiWindow* window, const ImVec2& delta)
{
window->Pos += delta;
window->ClipRect.Translate(delta);
window->OuterRectClipped.Translate(delta);
window->InnerMainRect.Translate(delta);
window->DC.CursorPos += delta;
window->DC.CursorStartPos += delta;
window->DC.CursorMaxPos += delta;
window->DC.LastItemRect.Translate(delta);
window->DC.LastItemDisplayRect.Translate(delta);
}
static void ScaleWindow(ImGuiWindow* window, float scale)
{
ImVec2 origin = window->Viewport->Pos;
window->Pos = ImFloor((window->Pos - origin) * scale + origin);
window->Size = ImFloor(window->Size * scale);
window->SizeFull = ImFloor(window->SizeFull * scale);
window->SizeContents = ImFloor(window->SizeContents * scale);
}
static bool IsWindowActiveAndVisible(ImGuiWindow* window)
{
return (window->Active) && (!window->Hidden);
}
static void ImGui::UpdateMouseInputs()
{
ImGuiContext& g = *GImGui;
// Round mouse position to avoid spreading non-rounded position (e.g. UpdateManualResize doesn't support them well)
if (IsMousePosValid(&g.IO.MousePos))
g.IO.MousePos = g.LastValidMousePos = ImFloor(g.IO.MousePos);
// If mouse just appeared or disappeared (usually denoted by -FLT_MAX components) we cancel out movement in MouseDelta
if (IsMousePosValid(&g.IO.MousePos) && IsMousePosValid(&g.IO.MousePosPrev))
g.IO.MouseDelta = g.IO.MousePos - g.IO.MousePosPrev;
else
g.IO.MouseDelta = ImVec2(0.0f, 0.0f);
if (g.IO.MouseDelta.x != 0.0f || g.IO.MouseDelta.y != 0.0f)
g.NavDisableMouseHover = false;
g.IO.MousePosPrev = g.IO.MousePos;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
g.IO.MouseClicked[i] = g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] < 0.0f;
g.IO.MouseReleased[i] = !g.IO.MouseDown[i] && g.IO.MouseDownDuration[i] >= 0.0f;
g.IO.MouseDownDurationPrev[i] = g.IO.MouseDownDuration[i];
g.IO.MouseDownDuration[i] = g.IO.MouseDown[i] ? (g.IO.MouseDownDuration[i] < 0.0f ? 0.0f : g.IO.MouseDownDuration[i] + g.IO.DeltaTime) : -1.0f;
g.IO.MouseDoubleClicked[i] = false;
if (g.IO.MouseClicked[i])
{
if ((float)(g.Time - g.IO.MouseClickedTime[i]) < g.IO.MouseDoubleClickTime)
{
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
if (ImLengthSqr(delta_from_click_pos) < g.IO.MouseDoubleClickMaxDist * g.IO.MouseDoubleClickMaxDist)
g.IO.MouseDoubleClicked[i] = true;
g.IO.MouseClickedTime[i] = -FLT_MAX; // so the third click isn't turned into a double-click
}
else
{
g.IO.MouseClickedTime[i] = g.Time;
}
g.IO.MouseClickedPos[i] = g.IO.MousePos;
g.IO.MouseDragMaxDistanceAbs[i] = ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = 0.0f;
}
else if (g.IO.MouseDown[i])
{
// Maintain the maximum distance we reaching from the initial click position, which is used with dragging threshold
ImVec2 delta_from_click_pos = IsMousePosValid(&g.IO.MousePos) ? (g.IO.MousePos - g.IO.MouseClickedPos[i]) : ImVec2(0.0f, 0.0f);
g.IO.MouseDragMaxDistanceSqr[i] = ImMax(g.IO.MouseDragMaxDistanceSqr[i], ImLengthSqr(delta_from_click_pos));
g.IO.MouseDragMaxDistanceAbs[i].x = ImMax(g.IO.MouseDragMaxDistanceAbs[i].x, delta_from_click_pos.x < 0.0f ? -delta_from_click_pos.x : delta_from_click_pos.x);
g.IO.MouseDragMaxDistanceAbs[i].y = ImMax(g.IO.MouseDragMaxDistanceAbs[i].y, delta_from_click_pos.y < 0.0f ? -delta_from_click_pos.y : delta_from_click_pos.y);
}
if (g.IO.MouseClicked[i]) // Clicking any mouse button reactivate mouse hovering which may have been deactivated by gamepad/keyboard navigation
g.NavDisableMouseHover = false;
}
}
void ImGui::UpdateMouseWheel()
{
ImGuiContext& g = *GImGui;
if (!g.HoveredWindow || g.HoveredWindow->Collapsed)
return;
if (g.IO.MouseWheel == 0.0f && g.IO.MouseWheelH == 0.0f)
return;
// If a child window has the ImGuiWindowFlags_NoScrollWithMouse flag, we give a chance to scroll its parent (unless either ImGuiWindowFlags_NoInputs or ImGuiWindowFlags_NoScrollbar are also set).
ImGuiWindow* window = g.HoveredWindow;
ImGuiWindow* scroll_window = window;
while ((scroll_window->Flags & ImGuiWindowFlags_ChildWindow) && (scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoScrollbar) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs) && scroll_window->ParentWindow)
scroll_window = scroll_window->ParentWindow;
const bool scroll_allowed = !(scroll_window->Flags & ImGuiWindowFlags_NoScrollWithMouse) && !(scroll_window->Flags & ImGuiWindowFlags_NoMouseInputs);
if (g.IO.MouseWheel != 0.0f)
{
if (g.IO.KeyCtrl && g.IO.FontAllowUserScaling)
{
// Zoom / Scale window
const float new_font_scale = ImClamp(window->FontWindowScale + g.IO.MouseWheel * 0.10f, 0.50f, 2.50f);
const float scale = new_font_scale / window->FontWindowScale;
window->FontWindowScale = new_font_scale;
const ImVec2 offset = window->Size * (1.0f - scale) * (g.IO.MousePos - window->Pos) / window->Size;
window->Pos += offset;
window->Size *= scale;
window->SizeFull *= scale;
}
else if (!g.IO.KeyCtrl && scroll_allowed)
{
// Mouse wheel vertical scrolling
float scroll_amount = 5 * scroll_window->CalcFontSize();
scroll_amount = (float)(int)ImMin(scroll_amount, (scroll_window->ContentsRegionRect.GetHeight() + scroll_window->WindowPadding.y * 2.0f) * 0.67f);
SetWindowScrollY(scroll_window, scroll_window->Scroll.y - g.IO.MouseWheel * scroll_amount);
}
}
if (g.IO.MouseWheelH != 0.0f && scroll_allowed && !g.IO.KeyCtrl)
{
// Mouse wheel horizontal scrolling (for hardware that supports it)
float scroll_amount = scroll_window->CalcFontSize();
SetWindowScrollX(scroll_window, scroll_window->Scroll.x - g.IO.MouseWheelH * scroll_amount);
}
}
// The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering, we want to dispatch inputs to the right target (imgui vs imgui+app)
void ImGui::UpdateHoveredWindowAndCaptureFlags()
{
ImGuiContext& g = *GImGui;
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
FindHoveredWindow();
IM_ASSERT(g.HoveredWindow == NULL || g.HoveredWindow == g.MovingWindow || g.HoveredWindow->Viewport == g.MouseViewport);
// Modal windows prevents cursor from hovering behind them.
ImGuiWindow* modal_window = GetFrontMostPopupModal();
if (modal_window)
if (g.HoveredRootWindow && !IsWindowChildOf(g.HoveredRootWindow, modal_window))
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
// Disabled mouse?
if (g.IO.ConfigFlags & ImGuiConfigFlags_NoMouse)
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
int mouse_earliest_button_down = -1;
bool mouse_any_down = false;
for (int i = 0; i < IM_ARRAYSIZE(g.IO.MouseDown); i++)
{
if (g.IO.MouseClicked[i])
g.IO.MouseDownOwned[i] = (g.HoveredWindow != NULL) || (!g.OpenPopupStack.empty());
mouse_any_down |= g.IO.MouseDown[i];
if (g.IO.MouseDown[i])
if (mouse_earliest_button_down == -1 || g.IO.MouseClickedTime[i] < g.IO.MouseClickedTime[mouse_earliest_button_down])
mouse_earliest_button_down = i;
}
const bool mouse_avail_to_imgui = (mouse_earliest_button_down == -1) || g.IO.MouseDownOwned[mouse_earliest_button_down];
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
const bool mouse_dragging_extern_payload = g.DragDropActive && (g.DragDropSourceFlags & ImGuiDragDropFlags_SourceExtern) != 0;
if (!mouse_avail_to_imgui && !mouse_dragging_extern_payload)
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to imgui, false = dispatch mouse info to imgui + app)
if (g.WantCaptureMouseNextFrame != -1)
g.IO.WantCaptureMouse = (g.WantCaptureMouseNextFrame != 0);
else
g.IO.WantCaptureMouse = (mouse_avail_to_imgui && (g.HoveredWindow != NULL || mouse_any_down)) || (!g.OpenPopupStack.empty());
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to imgui, false = dispatch keyboard info to imgui + app)
if (g.WantCaptureKeyboardNextFrame != -1)
g.IO.WantCaptureKeyboard = (g.WantCaptureKeyboardNextFrame != 0);
else
g.IO.WantCaptureKeyboard = (g.ActiveId != 0) || (modal_window != NULL);
if (g.IO.NavActive && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavNoCaptureKeyboard))
g.IO.WantCaptureKeyboard = true;
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
g.IO.WantTextInput = (g.WantTextInputNextFrame != -1) ? (g.WantTextInputNextFrame != 0) : false;
}
void ImGui::NewFrame()
{
IM_ASSERT(GImGui != NULL && "No current context. Did you call ImGui::CreateContext() or ImGui::SetCurrentContext()?");
ImGuiContext& g = *GImGui;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PreNewFrame(&g);
#endif
// Check user data
// (We pass an error message in the assert expression to make it visible to programmers who are not using a debugger, as most assert handlers display their argument)
IM_ASSERT(g.Initialized);
IM_ASSERT((g.IO.DeltaTime > 0.0f || g.FrameCount == 0) && "Need a positive DeltaTime!");
IM_ASSERT(g.IO.DisplaySize.x >= 0.0f && g.IO.DisplaySize.y >= 0.0f && "Invalid DisplaySize value!");
IM_ASSERT(g.IO.Fonts->Fonts.Size > 0 && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.IO.Fonts->Fonts[0]->IsLoaded() && "Font Atlas not built. Did you call io.Fonts->GetTexDataAsRGBA32() / GetTexDataAsAlpha8() ?");
IM_ASSERT(g.Style.CurveTessellationTol > 0.0f && "Invalid style setting!");
IM_ASSERT(g.Style.Alpha >= 0.0f && g.Style.Alpha <= 1.0f && "Invalid style setting. Alpha cannot be negative (allows us to avoid a few clamps in color computations)!");
IM_ASSERT((g.FrameCount == 0 || g.FrameCountEnded == g.FrameCount) && "Forgot to call Render() or EndFrame() at the end of the previous frame?");
for (int n = 0; n < ImGuiKey_COUNT; n++)
IM_ASSERT(g.IO.KeyMap[n] >= -1 && g.IO.KeyMap[n] < IM_ARRAYSIZE(g.IO.KeysDown) && "io.KeyMap[] contains an out of bound value (need to be 0..512, or -1 for unmapped key)");
// Perform simple check: required key mapping (we intentionally do NOT check all keys to not pressure user into setting up everything, but Space is required and was only recently added in 1.60 WIP)
if (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard)
IM_ASSERT(g.IO.KeyMap[ImGuiKey_Space] != -1 && "ImGuiKey_Space is not mapped, required for keyboard navigation.");
// Perform simple check: the beta io.ConfigWindowsResizeFromEdges option requires back-end to honor mouse cursor changes and set the ImGuiBackendFlags_HasMouseCursors flag accordingly.
if (g.IO.ConfigWindowsResizeFromEdges && !(g.IO.BackendFlags & ImGuiBackendFlags_HasMouseCursors))
g.IO.ConfigWindowsResizeFromEdges = false;
// Perform simple checks: multi-viewport and platform windows support
if (g.IO.ConfigFlags & ImGuiConfigFlags_ViewportsEnable)
{
if ((g.IO.BackendFlags & ImGuiBackendFlags_PlatformHasViewports) && (g.IO.BackendFlags & ImGuiBackendFlags_RendererHasViewports))
{
IM_ASSERT((g.FrameCount == 0 || g.FrameCount == g.FrameCountPlatformEnded) && "Forgot to call UpdatePlatformWindows() in main loop after EndFrame()? Check examples/ applications for reference.");
IM_ASSERT(g.PlatformIO.Platform_CreateWindow != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Platform_DestroyWindow != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Platform_GetWindowPos != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Platform_SetWindowPos != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Platform_GetWindowSize != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Platform_SetWindowSize != NULL && "Platform init didn't install handlers?");
IM_ASSERT(g.PlatformIO.Monitors.Size > 0 && "Platform init didn't setup Monitors list?");
IM_ASSERT((g.Viewports[0]->PlatformUserData != NULL || g.Viewports[0]->PlatformHandle != NULL) && "Platform init didn't setup main viewport.");
if (g.IO.ConfigDockingTransparentPayload && (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
IM_ASSERT(g.PlatformIO.Platform_SetWindowAlpha != NULL && "Platform_SetWindowAlpha handler is required to use io.ConfigDockingTransparent!");
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
IM_ASSERT(g.IO.RenderDrawListsFn == NULL); // Call ImGui::Render() then pass ImGui::GetDrawData() yourself to your render function!
#endif
}
else
{
// Disable feature, our back-ends do not support it
g.IO.ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable;
}
// Perform simple checks on platform monitor data + compute a total bounding box for quick early outs
for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
{
ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[monitor_n];
IM_ASSERT(mon.MainSize.x > 0.0f && mon.MainSize.y > 0.0f && "Monitor bounds not setup properly.");
IM_ASSERT(mon.WorkSize.x > 0.0f && mon.WorkSize.y > 0.0f && "Monitor bounds not setup properly. If you don't have work area information, just copy Min/Max into them.");
IM_ASSERT(mon.DpiScale != 0.0f);
}
}
// Load settings on first frame (if not explicitly loaded manually before)
if (!g.SettingsLoaded)
{
IM_ASSERT(g.SettingsWindows.empty());
if (g.IO.IniFilename)
LoadIniSettingsFromDisk(g.IO.IniFilename);
g.SettingsLoaded = true;
}
// Save settings (with a delay after the last modification, so we don't spam disk too much)
if (g.SettingsDirtyTimer > 0.0f)
{
g.SettingsDirtyTimer -= g.IO.DeltaTime;
if (g.SettingsDirtyTimer <= 0.0f)
{
if (g.IO.IniFilename != NULL)
SaveIniSettingsToDisk(g.IO.IniFilename);
else
g.IO.WantSaveIniSettings = true; // Let user know they can call SaveIniSettingsToMemory(). user will need to clear io.WantSaveIniSettings themselves.
g.SettingsDirtyTimer = 0.0f;
}
}
g.Time += g.IO.DeltaTime;
g.FrameScopeActive = true;
g.FrameCount += 1;
g.TooltipOverrideCount = 0;
g.WindowsActiveCount = 0;
g.ConfigFlagsForFrame = g.IO.ConfigFlags;
UpdateViewportsNewFrame();
// Setup current font and draw list shared data
// FIXME-VIEWPORT: the concept of a single ClipRectFullscreen is not ideal!
g.IO.Fonts->Locked = true;
SetCurrentFont(GetDefaultFont());
IM_ASSERT(g.Font->IsLoaded());
ImVec2 virtual_space_max(0,0);
for (int n = 0; n < g.Viewports.Size; n++)
virtual_space_max = ImMax(virtual_space_max, g.Viewports[n]->Pos + g.Viewports[n]->Size);
g.DrawListSharedData.ClipRectFullscreen = ImVec4(0.0f, 0.0f, virtual_space_max.x, virtual_space_max.y);
g.DrawListSharedData.CurveTessellationTol = g.Style.CurveTessellationTol;
// Setup Overlay draw list for the viewport.
// Mark rendering data as invalid to prevent user who may have a handle on it to use it.
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
viewport->DrawData = NULL;
viewport->DrawDataP.Clear();
}
// Drag and drop keep the source ID alive so even if the source disappear our state is consistent
if (g.DragDropActive && g.DragDropPayload.SourceId == g.ActiveId)
KeepAliveID(g.DragDropPayload.SourceId);
// Clear reference to active widget if the widget isn't alive anymore
if (!g.HoveredIdPreviousFrame)
g.HoveredIdTimer = 0.0f;
if (!g.HoveredIdPreviousFrame || (g.HoveredId && g.ActiveId == g.HoveredId))
g.HoveredIdNotActiveTimer = 0.0f;
if (g.HoveredId)
g.HoveredIdTimer += g.IO.DeltaTime;
if (g.HoveredId && g.ActiveId != g.HoveredId)
g.HoveredIdNotActiveTimer += g.IO.DeltaTime;
g.HoveredIdPreviousFrame = g.HoveredId;
g.HoveredId = 0;
g.HoveredIdAllowOverlap = false;
if (g.ActiveIdIsAlive != g.ActiveId && g.ActiveIdPreviousFrame == g.ActiveId && g.ActiveId != 0)
ClearActiveID();
if (g.ActiveId)
g.ActiveIdTimer += g.IO.DeltaTime;
g.LastActiveIdTimer += g.IO.DeltaTime;
g.ActiveIdPreviousFrame = g.ActiveId;
g.ActiveIdPreviousFrameWindow = g.ActiveIdWindow;
g.ActiveIdPreviousFrameHasBeenEdited = g.ActiveIdHasBeenEdited;
g.ActiveIdIsAlive = 0;
g.ActiveIdPreviousFrameIsAlive = false;
g.ActiveIdIsJustActivated = false;
if (g.ScalarAsInputTextId && g.ActiveId != g.ScalarAsInputTextId)
g.ScalarAsInputTextId = 0;
// Drag and drop
g.DragDropAcceptIdPrev = g.DragDropAcceptIdCurr;
g.DragDropAcceptIdCurr = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropWithinSourceOrTarget = false;
// Update keyboard input state
memcpy(g.IO.KeysDownDurationPrev, g.IO.KeysDownDuration, sizeof(g.IO.KeysDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.KeysDown); i++)
g.IO.KeysDownDuration[i] = g.IO.KeysDown[i] ? (g.IO.KeysDownDuration[i] < 0.0f ? 0.0f : g.IO.KeysDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Update gamepad/keyboard directional navigation
NavUpdate();
// Update mouse input state
UpdateMouseInputs();
// Calculate frame-rate for the user, as a purely luxurious feature
g.FramerateSecPerFrameAccum += g.IO.DeltaTime - g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx];
g.FramerateSecPerFrame[g.FramerateSecPerFrameIdx] = g.IO.DeltaTime;
g.FramerateSecPerFrameIdx = (g.FramerateSecPerFrameIdx + 1) % IM_ARRAYSIZE(g.FramerateSecPerFrame);
g.IO.Framerate = (g.FramerateSecPerFrameAccum > 0.0f) ? (1.0f / (g.FramerateSecPerFrameAccum / (float)IM_ARRAYSIZE(g.FramerateSecPerFrame))) : FLT_MAX;
// Undocking
// (needs to be before UpdateMouseMovingWindowNewFrame so the window is already offset and following the mouse on the detaching frame)
DockContextNewFrameUpdateUndocking(&g);
// Find hovered window
// (needs to be before UpdateMouseMovingWindowNewFrame so we fill g.HoveredWindowUnderMovingWindow on the mouse release frame)
UpdateHoveredWindowAndCaptureFlags();
// Handle user moving window with mouse (at the beginning of the frame to avoid input lag or sheering)
UpdateMouseMovingWindowNewFrame();
// Background darkening/whitening
if (GetFrontMostPopupModal() != NULL || (g.NavWindowingTarget != NULL && g.NavWindowingHighlightAlpha > 0.0f))
g.DimBgRatio = ImMin(g.DimBgRatio + g.IO.DeltaTime * 6.0f, 1.0f);
else
g.DimBgRatio = ImMax(g.DimBgRatio - g.IO.DeltaTime * 10.0f, 0.0f);
g.MouseCursor = ImGuiMouseCursor_Arrow;
g.WantCaptureMouseNextFrame = g.WantCaptureKeyboardNextFrame = g.WantTextInputNextFrame = -1;
g.PlatformImePos = ImVec2(1.0f, 1.0f); // OS Input Method Editor showing on top-left of our window by default
g.PlatformImePosViewport = NULL;
// Mouse wheel scrolling, scale
UpdateMouseWheel();
// Pressing TAB activate widget focus
if (g.ActiveId == 0 && g.NavWindow != NULL && g.NavWindow->Active && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab, false))
{
if (g.NavId != 0 && g.NavIdTabCounter != INT_MAX)
g.NavWindow->FocusIdxTabRequestNext = g.NavIdTabCounter + 1 + (g.IO.KeyShift ? -1 : 1);
else
g.NavWindow->FocusIdxTabRequestNext = g.IO.KeyShift ? -1 : 0;
}
g.NavIdTabCounter = INT_MAX;
// Mark all windows as not visible
IM_ASSERT(g.WindowsFocusOrder.Size == g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
window->WasActive = window->Active;
window->BeginCount = 0;
window->Active = false;
window->WriteAccessed = false;
}
// Closing the focused window restore focus to the first active root window in descending z-order
if (g.NavWindow && !g.NavWindow->WasActive)
FocusPreviousWindowIgnoringOne(NULL);
// No window should be open at the beginning of the frame.
// But in order to allow the user to call NewFrame() multiple times without calling Render(), we are doing an explicit clear.
g.CurrentWindowStack.resize(0);
g.BeginPopupStack.resize(0);
ClosePopupsOverWindow(g.NavWindow);
// Docking
DockContextNewFrameUpdateDocking(&g);
// Create implicit/fallback window - which we will only render it if the user has added something to it.
// We don't use "Debug" to avoid colliding with user trying to create a "Debug" window with custom flags.
// This fallback is particularly important as it avoid ImGui:: calls from crashing.
SetNextWindowSize(ImVec2(400,400), ImGuiCond_FirstUseEver);
Begin("Debug##Default");
g.FrameScopePushedImplicitWindow = true;
#ifdef IMGUI_ENABLE_TEST_ENGINE
ImGuiTestEngineHook_PostNewFrame(&g);
#endif
}
void ImGui::Initialize(ImGuiContext* context)
{
ImGuiContext& g = *context;
IM_ASSERT(!g.Initialized && !g.SettingsLoaded);
// Add .ini handle for ImGuiWindow type
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Window";
ini_handler.TypeHash = ImHashStr("Window", 0);
ini_handler.ReadOpenFn = SettingsHandlerWindow_ReadOpen;
ini_handler.ReadLineFn = SettingsHandlerWindow_ReadLine;
ini_handler.WriteAllFn = SettingsHandlerWindow_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
// Create default viewport
ImGuiViewportP* viewport = IM_NEW(ImGuiViewportP)();
viewport->ID = IMGUI_VIEWPORT_DEFAULT_ID;
viewport->Idx = 0;
g.Viewports.push_back(viewport);
g.PlatformIO.MainViewport = g.Viewports[0]; // Make it accessible in public-facing GetPlatformIO() immediately (before the first call to EndFrame)
g.PlatformIO.Viewports.push_back(g.Viewports[0]);
// Extensions
IM_ASSERT(g.DockContext == NULL);
DockContextInitialize(&g);
g.Initialized = true;
}
// This function is merely here to free heap allocations.
void ImGui::Shutdown(ImGuiContext* context)
{
// The fonts atlas can be used prior to calling NewFrame(), so we clear it even if g.Initialized is FALSE (which would happen if we never called NewFrame)
ImGuiContext& g = *context;
if (g.IO.Fonts && g.FontAtlasOwnedByContext)
{
g.IO.Fonts->Locked = false;
IM_DELETE(g.IO.Fonts);
}
g.IO.Fonts = NULL;
// Cleanup of other data are conditional on actually having initialized ImGui.
if (!g.Initialized)
return;
// Save settings (unless we haven't attempted to load them: CreateContext/DestroyContext without a call to NewFrame shouldn't save an empty file)
if (g.SettingsLoaded && g.IO.IniFilename != NULL)
{
ImGuiContext* backup_context = GImGui;
SetCurrentContext(context);
SaveIniSettingsToDisk(g.IO.IniFilename);
SetCurrentContext(backup_context);
}
// Destroy platform windows
ImGuiContext* backup_context = ImGui::GetCurrentContext();
SetCurrentContext(context);
DestroyPlatformWindows();
SetCurrentContext(backup_context);
// Shutdown extensions
IM_ASSERT(g.DockContext != NULL);
DockContextShutdown(&g);
// Clear everything else
for (int i = 0; i < g.Windows.Size; i++)
IM_DELETE(g.Windows[i]);
g.Windows.clear();
g.WindowsFocusOrder.clear();
g.WindowsSortBuffer.clear();
g.CurrentWindow = NULL;
g.CurrentWindowStack.clear();
g.WindowsById.Clear();
g.NavWindow = NULL;
g.HoveredWindow = g.HoveredRootWindow = g.HoveredWindowUnderMovingWindow = NULL;
g.ActiveIdWindow = g.ActiveIdPreviousFrameWindow = NULL;
g.MovingWindow = NULL;
g.ColorModifiers.clear();
g.StyleModifiers.clear();
g.FontStack.clear();
g.OpenPopupStack.clear();
g.BeginPopupStack.clear();
g.CurrentViewport = g.MouseViewport = g.MouseLastHoveredViewport = NULL;
for (int i = 0; i < g.Viewports.Size; i++)
IM_DELETE(g.Viewports[i]);
g.Viewports.clear();
g.PrivateClipboard.clear();
g.InputTextState.TextW.clear();
g.InputTextState.InitialText.clear();
g.InputTextState.TempBuffer.clear();
for (int i = 0; i < g.SettingsWindows.Size; i++)
IM_DELETE(g.SettingsWindows[i].Name);
g.SettingsWindows.clear();
g.SettingsHandlers.clear();
if (g.LogFile && g.LogFile != stdout)
{
fclose(g.LogFile);
g.LogFile = NULL;
}
g.LogClipboard.clear();
g.Initialized = false;
}
// FIXME: Add a more explicit sort order in the window structure.
static int IMGUI_CDECL ChildWindowComparer(const void* lhs, const void* rhs)
{
const ImGuiWindow* const a = *(const ImGuiWindow* const *)lhs;
const ImGuiWindow* const b = *(const ImGuiWindow* const *)rhs;
if (int d = (a->Flags & ImGuiWindowFlags_Popup) - (b->Flags & ImGuiWindowFlags_Popup))
return d;
if (int d = (a->Flags & ImGuiWindowFlags_Tooltip) - (b->Flags & ImGuiWindowFlags_Tooltip))
return d;
return (a->BeginOrderWithinParent - b->BeginOrderWithinParent);
}
static void AddWindowToSortBuffer(ImVector<ImGuiWindow*>* out_sorted_windows, ImGuiWindow* window)
{
out_sorted_windows->push_back(window);
if (window->Active)
{
int count = window->DC.ChildWindows.Size;
if (count > 1)
ImQsort(window->DC.ChildWindows.begin(), (size_t)count, sizeof(ImGuiWindow*), ChildWindowComparer);
for (int i = 0; i < count; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (child->Active)
AddWindowToSortBuffer(out_sorted_windows, child);
}
}
}
static void AddDrawListToDrawData(ImVector<ImDrawList*>* out_list, ImDrawList* draw_list)
{
if (draw_list->CmdBuffer.empty())
return;
// Remove trailing command if unused
ImDrawCmd& last_cmd = draw_list->CmdBuffer.back();
if (last_cmd.ElemCount == 0 && last_cmd.UserCallback == NULL)
{
draw_list->CmdBuffer.pop_back();
if (draw_list->CmdBuffer.empty())
return;
}
// Draw list sanity check. Detect mismatch between PrimReserve() calls and incrementing _VtxCurrentIdx, _VtxWritePtr etc. May trigger for you if you are using PrimXXX functions incorrectly.
IM_ASSERT(draw_list->VtxBuffer.Size == 0 || draw_list->_VtxWritePtr == draw_list->VtxBuffer.Data + draw_list->VtxBuffer.Size);
IM_ASSERT(draw_list->IdxBuffer.Size == 0 || draw_list->_IdxWritePtr == draw_list->IdxBuffer.Data + draw_list->IdxBuffer.Size);
IM_ASSERT((int)draw_list->_VtxCurrentIdx == draw_list->VtxBuffer.Size);
// Check that draw_list doesn't use more vertices than indexable (default ImDrawIdx = unsigned short = 2 bytes = 64K vertices per ImDrawList = per window)
// If this assert triggers because you are drawing lots of stuff manually:
// A) Make sure you are coarse clipping, because ImDrawList let all your vertices pass. You can use the Metrics window to inspect draw list contents.
// B) If you need/want meshes with more than 64K vertices, uncomment the '#define ImDrawIdx unsigned int' line in imconfig.h to set the index size to 4 bytes.
// You'll need to handle the 4-bytes indices to your renderer. For example, the OpenGL example code detect index size at compile-time by doing:
// glDrawElements(GL_TRIANGLES, (GLsizei)pcmd->ElemCount, sizeof(ImDrawIdx) == 2 ? GL_UNSIGNED_SHORT : GL_UNSIGNED_INT, idx_buffer_offset);
// Your own engine or render API may use different parameters or function calls to specify index sizes. 2 and 4 bytes indices are generally supported by most API.
// C) If for some reason you cannot use 4 bytes indices or don't want to, a workaround is to call BeginChild()/EndChild() before reaching the 64K limit to split your draw commands in multiple draw lists.
if (sizeof(ImDrawIdx) == 2)
IM_ASSERT(draw_list->_VtxCurrentIdx < (1 << 16) && "Too many vertices in ImDrawList using 16-bit indices. Read comment above");
out_list->push_back(draw_list);
}
static void AddWindowToDrawData(ImGuiWindow* window, int layer)
{
ImGuiContext& g = *GImGui;
g.IO.MetricsRenderWindows++;
AddDrawListToDrawData(&window->Viewport->DrawDataBuilder.Layers[layer], window->DrawList);
for (int i = 0; i < window->DC.ChildWindows.Size; i++)
{
ImGuiWindow* child = window->DC.ChildWindows[i];
if (IsWindowActiveAndVisible(child)) // Clipped children may have been marked not active
AddWindowToDrawData(child, layer);
}
}
// Layer is locked for the root window, however child windows may use a different viewport (e.g. extruding menu)
static void AddRootWindowToDrawData(ImGuiWindow* window)
{
int layer = (window->Flags & ImGuiWindowFlags_Tooltip) ? 1 : 0;
AddWindowToDrawData(window, layer);
}
void ImDrawDataBuilder::FlattenIntoSingleLayer()
{
int n = Layers[0].Size;
int size = n;
for (int i = 1; i < IM_ARRAYSIZE(Layers); i++)
size += Layers[i].Size;
Layers[0].resize(size);
for (int layer_n = 1; layer_n < IM_ARRAYSIZE(Layers); layer_n++)
{
ImVector<ImDrawList*>& layer = Layers[layer_n];
if (layer.empty())
continue;
memcpy(&Layers[0][n], &layer[0], layer.Size * sizeof(ImDrawList*));
n += layer.Size;
layer.resize(0);
}
}
static void SetupViewportDrawData(ImGuiViewportP* viewport, ImVector<ImDrawList*>* draw_lists)
{
ImDrawData* draw_data = &viewport->DrawDataP;
viewport->DrawData = draw_data; // Make publicly accessible
draw_data->Valid = true;
draw_data->CmdLists = (draw_lists->Size > 0) ? draw_lists->Data : NULL;
draw_data->CmdListsCount = draw_lists->Size;
draw_data->TotalVtxCount = draw_data->TotalIdxCount = 0;
draw_data->DisplayPos = viewport->Pos;
draw_data->DisplaySize = viewport->Size;
draw_data->FramebufferScale = ImGui::GetIO().DisplayFramebufferScale; // FIXME-VIEWPORT: This may vary on a per-monitor/viewport basis?
for (int n = 0; n < draw_lists->Size; n++)
{
draw_data->TotalVtxCount += draw_lists->Data[n]->VtxBuffer.Size;
draw_data->TotalIdxCount += draw_lists->Data[n]->IdxBuffer.Size;
}
}
// When using this function it is sane to ensure that float are perfectly rounded to integer values, to that e.g. (int)(max.x-min.x) in user's render produce correct result.
void ImGui::PushClipRect(const ImVec2& clip_rect_min, const ImVec2& clip_rect_max, bool intersect_with_current_clip_rect)
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PushClipRect(clip_rect_min, clip_rect_max, intersect_with_current_clip_rect);
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
void ImGui::PopClipRect()
{
ImGuiWindow* window = GetCurrentWindow();
window->DrawList->PopClipRect();
window->ClipRect = window->DrawList->_ClipRectStack.back();
}
static ImGuiWindow* FindFrontMostVisibleChildWindow(ImGuiWindow* window)
{
for (int n = window->DC.ChildWindows.Size - 1; n >= 0; n--)
if (IsWindowActiveAndVisible(window->DC.ChildWindows[n]))
return FindFrontMostVisibleChildWindow(window->DC.ChildWindows[n]);
return window;
}
static void ImGui::EndFrameDrawDimmedBackgrounds()
{
ImGuiContext& g = *GImGui;
// Draw modal whitening background on _other_ viewports than the one the modal is one
ImGuiWindow* modal_window = GetFrontMostPopupModal();
const bool dim_bg_for_modal = (modal_window != NULL);
const bool dim_bg_for_window_list = (g.NavWindowingTargetAnim != NULL);
if (dim_bg_for_modal || dim_bg_for_window_list)
for (int viewport_n = 0; viewport_n < g.Viewports.Size; viewport_n++)
{
ImGuiViewportP* viewport = g.Viewports[viewport_n];
if (modal_window && viewport == modal_window->Viewport)
continue;
if (g.NavWindowingList && viewport == g.NavWindowingList->Viewport)
continue;
if (g.NavWindowingTargetAnim && viewport == g.NavWindowingTargetAnim->Viewport)
continue;
ImDrawList* draw_list = GetOverlayDrawList(viewport);
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
draw_list->AddRectFilled(viewport->Pos, viewport->Pos + viewport->Size, dim_bg_col);
}
// Draw modal whitening background between CTRL-TAB list
if (dim_bg_for_window_list)
{
// Choose a draw list that will be front-most across all our children
ImGuiWindow* window = g.NavWindowingTargetAnim;
ImDrawList* draw_list = FindFrontMostVisibleChildWindow(window->RootWindow)->DrawList;
draw_list->PushClipRectFullScreen();
// Docking: draw modal whitening background on other nodes of a same dock tree
if (window->RootWindowDockStop->DockIsActive)
if (window->RootWindow != window->RootWindowDockStop)
RenderRectFilledWithHole(draw_list, window->RootWindow->Rect(), window->RootWindowDockStop->Rect(), GetColorU32(ImGuiCol_NavWindowingDimBg, g.DimBgRatio), g.Style.WindowRounding);
// Draw navigation selection/windowing rectangle border
float rounding = ImMax(window->WindowRounding, g.Style.WindowRounding);
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (bb.Contains(window->Viewport->GetRect())) // If a window fits the entire viewport, adjust its highlight inward
{
bb.Expand(-g.FontSize - 1.0f);
rounding = window->WindowRounding;
}
draw_list->AddRect(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha), rounding, ~0, 3.0f);
draw_list->PopClipRect();
}
}
// This is normally called by Render(). You may want to call it directly if you want to avoid calling Render() but the gain will be very minimal.
void ImGui::EndFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded == g.FrameCount) // Don't process EndFrame() multiple times.
return;
IM_ASSERT(g.FrameScopeActive && "Forgot to call ImGui::NewFrame()?");
// Notify OS when our Input Method Editor cursor has moved (e.g. CJK inputs using Microsoft IME)
if (g.PlatformIO.Platform_SetImeInputPos && (g.PlatformImeLastPos.x == FLT_MAX || ImLengthSqr(g.PlatformImePos - g.PlatformImeLastPos) > 0.0001f))
if (g.PlatformImePosViewport && g.PlatformImePosViewport->PlatformWindowCreated)
{
g.PlatformIO.Platform_SetImeInputPos(g.PlatformImePosViewport, g.PlatformImePos);
g.PlatformImeLastPos = g.PlatformImePos;
g.PlatformImePosViewport = NULL;
}
// Report when there is a mismatch of Begin/BeginChild vs End/EndChild calls. Important: Remember that the Begin/BeginChild API requires you
// to always call End/EndChild even if Begin/BeginChild returns false! (this is unfortunately inconsistent with most other Begin* API).
if (g.CurrentWindowStack.Size != 1)
{
if (g.CurrentWindowStack.Size > 1)
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you forget to call End/EndChild?");
while (g.CurrentWindowStack.Size > 1) // FIXME-ERRORHANDLING
End();
}
else
{
IM_ASSERT(g.CurrentWindowStack.Size == 1 && "Mismatched Begin/BeginChild vs End/EndChild calls: did you call End/EndChild too much?");
}
}
// Hide implicit/fallback "Debug" window if it hasn't been used
g.FrameScopePushedImplicitWindow = false;
if (g.CurrentWindow && !g.CurrentWindow->WriteAccessed)
g.CurrentWindow->Active = false;
End();
// Draw modal whitening background on _other_ viewports than the one the modal is one
EndFrameDrawDimmedBackgrounds();
// Show CTRL+TAB list window
if (g.NavWindowingTarget)
NavUpdateWindowingList();
SetCurrentViewport(NULL, NULL);
// Drag and Drop: Elapse payload (if delivered, or if source stops being submitted)
if (g.DragDropActive)
{
bool is_delivered = g.DragDropPayload.Delivery;
bool is_elapsed = (g.DragDropPayload.DataFrameCount + 1 < g.FrameCount) && ((g.DragDropSourceFlags & ImGuiDragDropFlags_SourceAutoExpirePayload) || !IsMouseDown(g.DragDropMouseButton));
if (is_delivered || is_elapsed)
ClearDragDrop();
}
// Drag and Drop: Fallback for source tooltip. This is not ideal but better than nothing.
if (g.DragDropActive && g.DragDropSourceFrameCount < g.FrameCount)
{
g.DragDropWithinSourceOrTarget = true;
SetTooltip("...");
g.DragDropWithinSourceOrTarget = false;
}
// End frame
g.FrameScopeActive = false;
g.FrameCountEnded = g.FrameCount;
// Initiate moving window + handle left-click and right-click focus
UpdateMouseMovingWindowEndFrame();
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
UpdateViewportsEndFrame();
// Sort the window list so that all child windows are after their parent
// We cannot do that on FocusWindow() because childs may not exist yet
g.WindowsSortBuffer.resize(0);
g.WindowsSortBuffer.reserve(g.Windows.Size);
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Active && (window->Flags & ImGuiWindowFlags_ChildWindow)) // if a child is active its parent will add it
continue;
AddWindowToSortBuffer(&g.WindowsSortBuffer, window);
}
// This usually assert if there is a mismatch between the ImGuiWindowFlags_ChildWindow / ParentWindow values and DC.ChildWindows[] in parents, aka we've done something wrong.
IM_ASSERT(g.Windows.Size == g.WindowsSortBuffer.Size);
g.Windows.swap(g.WindowsSortBuffer);
g.IO.MetricsActiveWindows = g.WindowsActiveCount;
// Unlock font atlas
g.IO.Fonts->Locked = false;
// Clear Input data for next frame
g.IO.MouseWheel = g.IO.MouseWheelH = 0.0f;
g.IO.InputQueueCharacters.resize(0);
memset(g.IO.NavInputs, 0, sizeof(g.IO.NavInputs));
}
void ImGui::Render()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
if (g.FrameCountEnded != g.FrameCount)
EndFrame();
g.FrameCountRendered = g.FrameCount;
// Gather ImDrawList to render (for each active window)
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = g.IO.MetricsRenderWindows = 0;
for (int n = 0; n != g.Viewports.Size; n++)
g.Viewports[n]->DrawDataBuilder.Clear();
ImGuiWindow* windows_to_render_front_most[2];
windows_to_render_front_most[0] = (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus)) ? g.NavWindowingTarget->RootWindow : NULL;
windows_to_render_front_most[1] = g.NavWindowingTarget ? g.NavWindowingList : NULL;
for (int n = 0; n != g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (IsWindowActiveAndVisible(window) && (window->Flags & ImGuiWindowFlags_ChildWindow) == 0 && window != windows_to_render_front_most[0] && window != windows_to_render_front_most[1])
AddRootWindowToDrawData(window);
}
for (int n = 0; n < IM_ARRAYSIZE(windows_to_render_front_most); n++)
if (windows_to_render_front_most[n] && IsWindowActiveAndVisible(windows_to_render_front_most[n])) // NavWindowingTarget is always temporarily displayed as the front-most window
AddRootWindowToDrawData(windows_to_render_front_most[n]);
// Draw software mouse cursor if requested
if (g.IO.MouseDrawCursor)
RenderMouseCursor(g.IO.MousePos, g.Style.MouseCursorScale, g.MouseCursor);
// Setup ImDrawData structures for end-user
g.IO.MetricsRenderVertices = g.IO.MetricsRenderIndices = 0;
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
viewport->DrawDataBuilder.FlattenIntoSingleLayer();
if (viewport->OverlayDrawList != NULL)
AddDrawListToDrawData(&viewport->DrawDataBuilder.Layers[0], GetOverlayDrawList(viewport));
SetupViewportDrawData(viewport, &viewport->DrawDataBuilder.Layers[0]);
g.IO.MetricsRenderVertices += viewport->DrawData->TotalVtxCount;
g.IO.MetricsRenderIndices += viewport->DrawData->TotalIdxCount;
}
// (Legacy) Call the Render callback function. The current prefer way is to let the user retrieve GetDrawData() and call the render function themselves.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
if (g.Viewports[0]->DrawData->CmdListsCount > 0 && g.IO.RenderDrawListsFn != NULL)
g.IO.RenderDrawListsFn(g.Viewports[0]->DrawData);
#endif
}
// Calculate text size. Text can be multi-line. Optionally ignore text after a ## marker.
// CalcTextSize("") should return ImVec2(0.0f, GImGui->FontSize)
ImVec2 ImGui::CalcTextSize(const char* text, const char* text_end, bool hide_text_after_double_hash, float wrap_width)
{
ImGuiContext& g = *GImGui;
const char* text_display_end;
if (hide_text_after_double_hash)
text_display_end = FindRenderedTextEnd(text, text_end); // Hide anything after a '##' string
else
text_display_end = text_end;
ImFont* font = g.Font;
const float font_size = g.FontSize;
if (text == text_display_end)
return ImVec2(0.0f, font_size);
ImVec2 text_size = font->CalcTextSizeA(font_size, FLT_MAX, wrap_width, text, text_display_end, NULL);
// Round
text_size.x = (float)(int)(text_size.x + 0.95f);
return text_size;
}
// Helper to calculate coarse clipping of large list of evenly sized items.
// NB: Prefer using the ImGuiListClipper higher-level helper if you can! Read comments and instructions there on how those use this sort of pattern.
// NB: 'items_count' is only used to clamp the result, if you don't know your count you can use INT_MAX
void ImGui::CalcListClipping(int items_count, float items_height, int* out_items_display_start, int* out_items_display_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.LogEnabled)
{
// If logging is active, do not perform any clipping
*out_items_display_start = 0;
*out_items_display_end = items_count;
return;
}
if (window->SkipItems)
{
*out_items_display_start = *out_items_display_end = 0;
return;
}
// We create the union of the ClipRect and the NavScoringRect which at worst should be 1 page away from ClipRect
ImRect unclipped_rect = window->ClipRect;
if (g.NavMoveRequest)
unclipped_rect.Add(g.NavScoringRectScreen);
const ImVec2 pos = window->DC.CursorPos;
int start = (int)((unclipped_rect.Min.y - pos.y) / items_height);
int end = (int)((unclipped_rect.Max.y - pos.y) / items_height);
// When performing a navigation request, ensure we have one item extra in the direction we are moving to
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Up)
start--;
if (g.NavMoveRequest && g.NavMoveClipDir == ImGuiDir_Down)
end++;
start = ImClamp(start, 0, items_count);
end = ImClamp(end + 1, start, items_count);
*out_items_display_start = start;
*out_items_display_end = end;
}
// Find window given position, search front-to-back
// FIXME: Note that we have an inconsequential lag here: OuterRectClipped is updated in Begin(), so windows moved programatically
// with SetWindowPos() and not SetNextWindowPos() will have that rectangle lagging by a frame at the time FindHoveredWindow() is
// called, aka before the next Begin(). Moving window isn't affected.
static void FindHoveredWindow()
{
ImGuiContext& g = *GImGui;
// Special handling for the window being moved: Ignore the mouse viewport check (because it may reset/lose its viewport during the undocking frame)
ImGuiViewportP* moving_window_viewport = g.MovingWindow ? g.MovingWindow->Viewport : NULL;
if (g.MovingWindow)
g.MovingWindow->Viewport = g.MouseViewport;
ImGuiWindow* hovered_window = NULL;
ImGuiWindow* hovered_window_ignoring_moving_window = NULL;
if (g.MovingWindow && !(g.MovingWindow->Flags & ImGuiWindowFlags_NoMouseInputs))
hovered_window = g.MovingWindow;
ImVec2 padding_regular = g.Style.TouchExtraPadding;
ImVec2 padding_for_resize_from_edges = g.IO.ConfigWindowsResizeFromEdges ? ImMax(g.Style.TouchExtraPadding, ImVec2(WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS)) : padding_regular;
for (int i = g.Windows.Size - 1; i >= 0; i--)
{
ImGuiWindow* window = g.Windows[i];
if (!window->Active || window->Hidden)
continue;
if (window->Flags & ImGuiWindowFlags_NoMouseInputs)
continue;
IM_ASSERT(window->Viewport);
if (window->Viewport != g.MouseViewport)
continue;
// Using the clipped AABB, a child window will typically be clipped by its parent (not always)
ImRect bb(window->OuterRectClipped);
if ((window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_NoResize))
bb.Expand(padding_regular);
else
bb.Expand(padding_for_resize_from_edges);
if (!bb.Contains(g.IO.MousePos))
continue;
if (window->HitTestHoleSize.x != 0)
{
// FIXME: Consider generalizing hit-testing override (with more generic data, callback, etc.) (#1512)
ImRect hole_bb((float)(window->HitTestHoleOffset.x), (float)(window->HitTestHoleOffset.y),
(float)(window->HitTestHoleOffset.x + window->HitTestHoleSize.x), (float)(window->HitTestHoleOffset.y + window->HitTestHoleSize.y));
if (hole_bb.Contains(g.IO.MousePos - window->Pos))
continue;
}
if (hovered_window == NULL)
hovered_window = window;
if (hovered_window_ignoring_moving_window == NULL && (!g.MovingWindow || window->RootWindow != g.MovingWindow->RootWindow))
hovered_window_ignoring_moving_window = window;
if (hovered_window && hovered_window_ignoring_moving_window)
break;
}
g.HoveredWindow = hovered_window;
g.HoveredRootWindow = g.HoveredWindow ? g.HoveredWindow->RootWindow : NULL;
g.HoveredWindowUnderMovingWindow = hovered_window_ignoring_moving_window;
if (g.MovingWindow)
g.MovingWindow->Viewport = moving_window_viewport;
}
// Test if mouse cursor is hovering given rectangle
// NB- Rectangle is clipped by our current clip setting
// NB- Expand the rectangle to be generous on imprecise inputs systems (g.Style.TouchExtraPadding)
bool ImGui::IsMouseHoveringRect(const ImVec2& r_min, const ImVec2& r_max, bool clip)
{
ImGuiContext& g = *GImGui;
// Clip
ImRect rect_clipped(r_min, r_max);
if (clip)
rect_clipped.ClipWith(g.CurrentWindow->ClipRect);
// Expand for touch input
const ImRect rect_for_touch(rect_clipped.Min - g.Style.TouchExtraPadding, rect_clipped.Max + g.Style.TouchExtraPadding);
if (!rect_for_touch.Contains(g.IO.MousePos))
return false;
if (!g.MouseViewport->GetRect().Overlaps(rect_clipped))
return false;
return true;
}
int ImGui::GetKeyIndex(ImGuiKey imgui_key)
{
IM_ASSERT(imgui_key >= 0 && imgui_key < ImGuiKey_COUNT);
return GImGui->IO.KeyMap[imgui_key];
}
// Note that imgui doesn't know the semantic of each entry of io.KeysDown[]. Use your own indices/enums according to how your back-end/engine stored them into io.KeysDown[]!
bool ImGui::IsKeyDown(int user_key_index)
{
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(GImGui->IO.KeysDown));
return GImGui->IO.KeysDown[user_key_index];
}
int ImGui::CalcTypematicPressedRepeatAmount(float t, float t_prev, float repeat_delay, float repeat_rate)
{
if (t == 0.0f)
return 1;
if (t <= repeat_delay || repeat_rate <= 0.0f)
return 0;
const int count = (int)((t - repeat_delay) / repeat_rate) - (int)((t_prev - repeat_delay) / repeat_rate);
return (count > 0) ? count : 0;
}
int ImGui::GetKeyPressedAmount(int key_index, float repeat_delay, float repeat_rate)
{
ImGuiContext& g = *GImGui;
if (key_index < 0)
return 0;
IM_ASSERT(key_index >= 0 && key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[key_index];
return CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, repeat_delay, repeat_rate);
}
bool ImGui::IsKeyPressed(int user_key_index, bool repeat)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0)
return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
const float t = g.IO.KeysDownDuration[user_key_index];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
return GetKeyPressedAmount(user_key_index, g.IO.KeyRepeatDelay, g.IO.KeyRepeatRate) > 0;
return false;
}
bool ImGui::IsKeyReleased(int user_key_index)
{
ImGuiContext& g = *GImGui;
if (user_key_index < 0) return false;
IM_ASSERT(user_key_index >= 0 && user_key_index < IM_ARRAYSIZE(g.IO.KeysDown));
return g.IO.KeysDownDurationPrev[user_key_index] >= 0.0f && !g.IO.KeysDown[user_key_index];
}
bool ImGui::IsMouseDown(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDown[button];
}
bool ImGui::IsAnyMouseDown()
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < IM_ARRAYSIZE(g.IO.MouseDown); n++)
if (g.IO.MouseDown[n])
return true;
return false;
}
bool ImGui::IsMouseClicked(int button, bool repeat)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
const float t = g.IO.MouseDownDuration[button];
if (t == 0.0f)
return true;
if (repeat && t > g.IO.KeyRepeatDelay)
{
float delay = g.IO.KeyRepeatDelay, rate = g.IO.KeyRepeatRate;
if ((ImFmod(t - delay, rate) > rate*0.5f) != (ImFmod(t - delay - g.IO.DeltaTime, rate) > rate*0.5f))
return true;
}
return false;
}
bool ImGui::IsMouseReleased(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseReleased[button];
}
bool ImGui::IsMouseDoubleClicked(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
return g.IO.MouseDoubleClicked[button];
}
bool ImGui::IsMouseDragging(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (!g.IO.MouseDown[button])
return false;
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
return g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold;
}
ImVec2 ImGui::GetMousePos()
{
return GImGui->IO.MousePos;
}
// NB: prefer to call right after BeginPopup(). At the time Selectable/MenuItem is activated, the popup is already closed!
ImVec2 ImGui::GetMousePosOnOpeningCurrentPopup()
{
ImGuiContext& g = *GImGui;
if (g.BeginPopupStack.Size > 0)
return g.OpenPopupStack[g.BeginPopupStack.Size-1].OpenMousePos;
return g.IO.MousePos;
}
// We typically use ImVec2(-FLT_MAX,-FLT_MAX) to denote an invalid mouse position.
bool ImGui::IsMousePosValid(const ImVec2* mouse_pos)
{
// The assert is only to silence a false-positive in XCode Static Analysis.
// Because GImGui is not dereferenced in every code path, the static analyzer assume that it may be NULL (which it doesn't for other functions).
IM_ASSERT(GImGui != NULL);
const float MOUSE_INVALID = -256000.0f;
ImVec2 p = mouse_pos ? *mouse_pos : GImGui->IO.MousePos;
return p.x >= MOUSE_INVALID && p.y >= MOUSE_INVALID;
}
// Return the delta from the initial clicking position.
// This is locked and return 0.0f until the mouse moves past a distance threshold at least once.
// NB: This is only valid if IsMousePosValid(). Back-ends in theory should always keep mouse position valid when dragging even outside the client window.
ImVec2 ImGui::GetMouseDragDelta(int button, float lock_threshold)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
if (lock_threshold < 0.0f)
lock_threshold = g.IO.MouseDragThreshold;
if (g.IO.MouseDown[button])
if (g.IO.MouseDragMaxDistanceSqr[button] >= lock_threshold * lock_threshold)
return g.IO.MousePos - g.IO.MouseClickedPos[button]; // Assume we can only get active with left-mouse button (at the moment).
return ImVec2(0.0f, 0.0f);
}
void ImGui::ResetMouseDragDelta(int button)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(button >= 0 && button < IM_ARRAYSIZE(g.IO.MouseDown));
// NB: We don't need to reset g.IO.MouseDragMaxDistanceSqr
g.IO.MouseClickedPos[button] = g.IO.MousePos;
}
ImGuiMouseCursor ImGui::GetMouseCursor()
{
return GImGui->MouseCursor;
}
void ImGui::SetMouseCursor(ImGuiMouseCursor cursor_type)
{
GImGui->MouseCursor = cursor_type;
}
void ImGui::CaptureKeyboardFromApp(bool capture)
{
GImGui->WantCaptureKeyboardNextFrame = capture ? 1 : 0;
}
void ImGui::CaptureMouseFromApp(bool capture)
{
GImGui->WantCaptureMouseNextFrame = capture ? 1 : 0;
}
bool ImGui::IsItemActive()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
return g.ActiveId == window->DC.LastItemId;
}
return false;
}
bool ImGui::IsItemActivated()
{
ImGuiContext& g = *GImGui;
if (g.ActiveId)
{
ImGuiWindow* window = g.CurrentWindow;
if (g.ActiveId == window->DC.LastItemId && g.ActiveIdPreviousFrame != window->DC.LastItemId)
return true;
}
return false;
}
bool ImGui::IsItemDeactivated()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return (g.ActiveIdPreviousFrame == window->DC.LastItemId && g.ActiveIdPreviousFrame != 0 && g.ActiveId != window->DC.LastItemId);
}
bool ImGui::IsItemDeactivatedAfterEdit()
{
ImGuiContext& g = *GImGui;
return IsItemDeactivated() && (g.ActiveIdPreviousFrameHasBeenEdited || (g.ActiveId == 0 && g.ActiveIdHasBeenEdited));
}
bool ImGui::IsItemFocused()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavId == 0 || g.NavDisableHighlight || g.NavId != window->DC.LastItemId)
return false;
// Special handling for the dummy item after Begin() which represent the title bar or tab.
// When the window is collapsed (SkipItems==true) that last item will never be overwritten so we need to detect the case.
if (window->DC.LastItemId == window->ID && window->WriteAccessed)
return false;
return true;
}
bool ImGui::IsItemClicked(int mouse_button)
{
return IsMouseClicked(mouse_button) && IsItemHovered(ImGuiHoveredFlags_None);
}
bool ImGui::IsAnyItemHovered()
{
ImGuiContext& g = *GImGui;
return g.HoveredId != 0 || g.HoveredIdPreviousFrame != 0;
}
bool ImGui::IsAnyItemActive()
{
ImGuiContext& g = *GImGui;
return g.ActiveId != 0;
}
bool ImGui::IsAnyItemFocused()
{
ImGuiContext& g = *GImGui;
return g.NavId != 0 && !g.NavDisableHighlight;
}
bool ImGui::IsItemVisible()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ClipRect.Overlaps(window->DC.LastItemRect);
}
bool ImGui::IsItemEdited()
{
ImGuiWindow* window = GetCurrentWindowRead();
return (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_Edited) != 0;
}
// Allow last item to be overlapped by a subsequent item. Both may be activated during the same frame before the later one takes priority.
void ImGui::SetItemAllowOverlap()
{
ImGuiContext& g = *GImGui;
if (g.HoveredId == g.CurrentWindow->DC.LastItemId)
g.HoveredIdAllowOverlap = true;
if (g.ActiveId == g.CurrentWindow->DC.LastItemId)
g.ActiveIdAllowOverlap = true;
}
ImVec2 ImGui::GetItemRectMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Min;
}
ImVec2 ImGui::GetItemRectMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.Max;
}
ImVec2 ImGui::GetItemRectSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.LastItemRect.GetSize();
}
static bool ImGui::BeginChildEx(const char* name, ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
flags |= ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_ChildWindow|ImGuiWindowFlags_NoDocking;
flags |= (parent_window->Flags & ImGuiWindowFlags_NoMove); // Inherit the NoMove flag
// Size
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
const int auto_fit_axises = ((size.x == 0.0f) ? (1 << ImGuiAxis_X) : 0x00) | ((size.y == 0.0f) ? (1 << ImGuiAxis_Y) : 0x00);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
SetNextWindowSize(size);
// Build up name. If you need to append to a same child from multiple location in the ID stack, use BeginChild(ImGuiID id) with a stable value.
char title[256];
if (name)
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%s_%08X", parent_window->Name, name, id);
else
ImFormatString(title, IM_ARRAYSIZE(title), "%s/%08X", parent_window->Name, id);
const float backup_border_size = g.Style.ChildBorderSize;
if (!border)
g.Style.ChildBorderSize = 0.0f;
bool ret = Begin(title, NULL, flags);
g.Style.ChildBorderSize = backup_border_size;
ImGuiWindow* child_window = g.CurrentWindow;
child_window->ChildId = id;
child_window->AutoFitChildAxises = auto_fit_axises;
// Set the cursor to handle case where the user called SetNextWindowPos()+BeginChild() manually.
// While this is not really documented/defined, it seems that the expected thing to do.
if (child_window->BeginCount == 1)
parent_window->DC.CursorPos = child_window->Pos;
// Process navigation-in immediately so NavInit can run on first frame
if (g.NavActivateId == id && !(flags & ImGuiWindowFlags_NavFlattened) && (child_window->DC.NavLayerActiveMask != 0 || child_window->DC.NavHasScroll))
{
FocusWindow(child_window);
NavInitWindow(child_window, false);
SetActiveID(id+1, child_window); // Steal ActiveId with a dummy id so that key-press won't activate child item
g.ActiveIdSource = ImGuiInputSource_Nav;
}
return ret;
}
bool ImGui::BeginChild(const char* str_id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
ImGuiWindow* window = GetCurrentWindow();
return BeginChildEx(str_id, window->GetID(str_id), size_arg, border, extra_flags);
}
bool ImGui::BeginChild(ImGuiID id, const ImVec2& size_arg, bool border, ImGuiWindowFlags extra_flags)
{
IM_ASSERT(id != 0);
return BeginChildEx(NULL, id, size_arg, border, extra_flags);
}
void ImGui::EndChild()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(window->Flags & ImGuiWindowFlags_ChildWindow); // Mismatched BeginChild()/EndChild() callss
if (window->BeginCount > 1)
{
End();
}
else
{
ImVec2 sz = window->Size;
if (window->AutoFitChildAxises & (1 << ImGuiAxis_X)) // Arbitrary minimum zero-ish child size of 4.0f causes less trouble than a 0.0f
sz.x = ImMax(4.0f, sz.x);
if (window->AutoFitChildAxises & (1 << ImGuiAxis_Y))
sz.y = ImMax(4.0f, sz.y);
End();
ImGuiWindow* parent_window = g.CurrentWindow;
ImRect bb(parent_window->DC.CursorPos, parent_window->DC.CursorPos + sz);
ItemSize(sz);
if ((window->DC.NavLayerActiveMask != 0 || window->DC.NavHasScroll) && !(window->Flags & ImGuiWindowFlags_NavFlattened))
{
ItemAdd(bb, window->ChildId);
RenderNavHighlight(bb, window->ChildId);
// When browsing a window that has no activable items (scroll only) we keep a highlight on the child
if (window->DC.NavLayerActiveMask == 0 && window == g.NavWindow)
RenderNavHighlight(ImRect(bb.Min - ImVec2(2,2), bb.Max + ImVec2(2,2)), g.NavId, ImGuiNavHighlightFlags_TypeThin);
}
else
{
// Not navigable into
ItemAdd(bb, 0);
}
}
}
// Helper to create a child window / scrolling region that looks like a normal widget frame.
bool ImGui::BeginChildFrame(ImGuiID id, const ImVec2& size, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
PushStyleColor(ImGuiCol_ChildBg, style.Colors[ImGuiCol_FrameBg]);
PushStyleVar(ImGuiStyleVar_ChildRounding, style.FrameRounding);
PushStyleVar(ImGuiStyleVar_ChildBorderSize, style.FrameBorderSize);
PushStyleVar(ImGuiStyleVar_WindowPadding, style.FramePadding);
bool ret = BeginChild(id, size, true, ImGuiWindowFlags_NoMove | ImGuiWindowFlags_AlwaysUseWindowPadding | extra_flags);
PopStyleVar(3);
PopStyleColor();
return ret;
}
void ImGui::EndChildFrame()
{
EndChild();
}
// Save and compare stack sizes on Begin()/End() to detect usage errors
static void CheckStacksSize(ImGuiWindow* window, bool write)
{
// NOT checking: DC.ItemWidth, DC.AllowKeyboardFocus, DC.ButtonRepeat, DC.TextWrapPos (per window) to allow user to conveniently push once and not pop (they are cleared on Begin)
ImGuiContext& g = *GImGui;
short* p_backup = &window->DC.StackSizesBackup[0];
{ int current = window->IDStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "PushID/PopID or TreeNode/TreePop Mismatch!"); p_backup++; } // Too few or too many PopID()/TreePop()
{ int current = window->DC.GroupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginGroup/EndGroup Mismatch!"); p_backup++; } // Too few or too many EndGroup()
{ int current = g.BeginPopupStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup == current && "BeginMenu/EndMenu or BeginPopup/EndPopup Mismatch"); p_backup++;}// Too few or too many EndMenu()/EndPopup()
// For color, style and font stacks there is an incentive to use Push/Begin/Pop/.../End patterns, so we relax our checks a little to allow them.
{ int current = g.ColorModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleColor/PopStyleColor Mismatch!"); p_backup++; } // Too few or too many PopStyleColor()
{ int current = g.StyleModifiers.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushStyleVar/PopStyleVar Mismatch!"); p_backup++; } // Too few or too many PopStyleVar()
{ int current = g.FontStack.Size; if (write) *p_backup = (short)current; else IM_ASSERT(*p_backup >= current && "PushFont/PopFont Mismatch!"); p_backup++; } // Too few or too many PopFont()
IM_ASSERT(p_backup == window->DC.StackSizesBackup + IM_ARRAYSIZE(window->DC.StackSizesBackup));
}
static void SetWindowConditionAllowFlags(ImGuiWindow* window, ImGuiCond flags, bool enabled)
{
window->SetWindowPosAllowFlags = enabled ? (window->SetWindowPosAllowFlags | flags) : (window->SetWindowPosAllowFlags & ~flags);
window->SetWindowSizeAllowFlags = enabled ? (window->SetWindowSizeAllowFlags | flags) : (window->SetWindowSizeAllowFlags & ~flags);
window->SetWindowCollapsedAllowFlags = enabled ? (window->SetWindowCollapsedAllowFlags | flags) : (window->SetWindowCollapsedAllowFlags & ~flags);
window->SetWindowDockAllowFlags = enabled ? (window->SetWindowDockAllowFlags | flags) : (window->SetWindowDockAllowFlags & ~flags);
}
ImGuiWindow* ImGui::FindWindowByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return (ImGuiWindow*)g.WindowsById.GetVoidPtr(id);
}
ImGuiWindow* ImGui::FindWindowByName(const char* name)
{
ImGuiID id = ImHashStr(name, 0);
return FindWindowByID(id);
}
static ImGuiWindow* CreateNewWindow(const char* name, ImVec2 size, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
// Create window the first time
ImGuiWindow* window = IM_NEW(ImGuiWindow)(&g, name);
window->Flags = flags;
g.WindowsById.SetVoidPtr(window->ID, window);
// Default/arbitrary window position. Use SetNextWindowPos() with the appropriate condition flag to change the initial position of a window.
ImGuiViewport* main_viewport = ImGui::GetMainViewport();
window->Pos = main_viewport->Pos + ImVec2(60, 60);
// User can disable loading and saving of settings. Tooltip and child windows also don't store settings.
if (!(flags & ImGuiWindowFlags_NoSavedSettings))
if (ImGuiWindowSettings* settings = ImGui::FindWindowSettings(window->ID))
{
// Retrieve settings from .ini file
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
SetWindowConditionAllowFlags(window, ImGuiCond_FirstUseEver, false);
if (settings->ViewportId)
{
window->ViewportId = settings->ViewportId;
window->ViewportPos = settings->ViewportPos;
}
else
{
window->ViewportPos = main_viewport->Pos;
}
window->Pos = ImFloor(settings->Pos + window->ViewportPos);
window->Collapsed = settings->Collapsed;
if (ImLengthSqr(settings->Size) > 0.00001f)
size = ImFloor(settings->Size);
window->DockId = settings->DockId;
window->DockOrder = settings->DockOrder;
}
window->Size = window->SizeFull = window->SizeFullAtLastBegin = ImFloor(size);
window->DC.CursorMaxPos = window->Pos; // So first call to CalcSizeContents() doesn't return crazy values
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) != 0)
{
window->AutoFitFramesX = window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
else
{
if (window->Size.x <= 0.0f)
window->AutoFitFramesX = 2;
if (window->Size.y <= 0.0f)
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = (window->AutoFitFramesX > 0) || (window->AutoFitFramesY > 0);
}
g.WindowsFocusOrder.push_back(window);
if (flags & ImGuiWindowFlags_NoBringToFrontOnFocus)
g.Windows.push_front(window); // Quite slow but rare and only once
else
g.Windows.push_back(window);
return window;
}
static ImGuiWindow* GetWindowForTitleDisplay(ImGuiWindow* window)
{
return window->DockNodeAsHost ? window->DockNodeAsHost->VisibleWindow : window;
}
static ImGuiWindow* GetWindowForTitleAndMenuHeight(ImGuiWindow* window)
{
return (window->DockNodeAsHost && window->DockNodeAsHost->VisibleWindow) ? window->DockNodeAsHost->VisibleWindow : window;
}
static ImVec2 CalcSizeAfterConstraint(ImGuiWindow* window, ImVec2 new_size)
{
ImGuiContext& g = *GImGui;
if (g.NextWindowData.SizeConstraintCond != 0)
{
// Using -1,-1 on either X/Y axis to preserve the current size.
ImRect cr = g.NextWindowData.SizeConstraintRect;
new_size.x = (cr.Min.x >= 0 && cr.Max.x >= 0) ? ImClamp(new_size.x, cr.Min.x, cr.Max.x) : window->SizeFull.x;
new_size.y = (cr.Min.y >= 0 && cr.Max.y >= 0) ? ImClamp(new_size.y, cr.Min.y, cr.Max.y) : window->SizeFull.y;
if (g.NextWindowData.SizeCallback)
{
ImGuiSizeCallbackData data;
data.UserData = g.NextWindowData.SizeCallbackUserData;
data.Pos = window->Pos;
data.CurrentSize = window->SizeFull;
data.DesiredSize = new_size;
g.NextWindowData.SizeCallback(&data);
new_size = data.DesiredSize;
}
}
// Minimum size
if (!(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysAutoResize)))
{
ImGuiWindow* window_for_height = GetWindowForTitleAndMenuHeight(window);
new_size = ImMax(new_size, g.Style.WindowMinSize);
new_size.y = ImMax(new_size.y, window_for_height->TitleBarHeight() + window_for_height->MenuBarHeight() + ImMax(0.0f, g.Style.WindowRounding - 1.0f)); // Reduce artifacts with very small windows
}
return new_size;
}
static ImVec2 CalcSizeContents(ImGuiWindow* window)
{
if (window->Collapsed)
if (window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
return window->SizeContents;
if (window->Hidden && window->HiddenFramesForResize == 0 && window->HiddenFramesRegular > 0)
return window->SizeContents;
ImVec2 sz;
sz.x = (float)(int)((window->SizeContentsExplicit.x != 0.0f) ? window->SizeContentsExplicit.x : (window->DC.CursorMaxPos.x - window->Pos.x + window->Scroll.x));
sz.y = (float)(int)((window->SizeContentsExplicit.y != 0.0f) ? window->SizeContentsExplicit.y : (window->DC.CursorMaxPos.y - window->Pos.y + window->Scroll.y));
return sz + window->WindowPadding;
}
static ImVec2 CalcSizeAutoFit(ImGuiWindow* window, const ImVec2& size_contents)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Tooltip always resize
return size_contents;
}
else
{
// Maximum window size is determined by the viewport size or monitor size
const bool is_popup = (window->Flags & ImGuiWindowFlags_Popup) != 0;
const bool is_menu = (window->Flags & ImGuiWindowFlags_ChildMenu) != 0;
ImVec2 size_min = style.WindowMinSize;
if (is_popup || is_menu) // Popups and menus bypass style.WindowMinSize by default, but we give then a non-zero minimum size to facilitate understanding problematic cases (e.g. empty popups)
size_min = ImMin(size_min, ImVec2(4.0f, 4.0f));
ImVec2 avail_size = window->Viewport->Size;
if (window->ViewportOwned)
avail_size = ImVec2(FLT_MAX, FLT_MAX);
const int monitor_idx = window->ViewportAllowPlatformMonitorExtend;
if (monitor_idx >= 0 && monitor_idx < g.PlatformIO.Monitors.Size)
avail_size = g.PlatformIO.Monitors[monitor_idx].WorkSize;
ImVec2 size_auto_fit = ImClamp(size_contents, size_min, ImMax(size_min, avail_size - g.Style.DisplaySafeAreaPadding * 2.0f));
// When the window cannot fit all contents (either because of constraints, either because screen is too small),
// we are growing the size on the other axis to compensate for expected scrollbar. FIXME: Might turn bigger than ViewportSize-WindowPadding.
ImVec2 size_auto_fit_after_constraint = CalcSizeAfterConstraint(window, size_auto_fit);
if (size_auto_fit_after_constraint.x < size_contents.x && !(window->Flags & ImGuiWindowFlags_NoScrollbar) && (window->Flags & ImGuiWindowFlags_HorizontalScrollbar))
size_auto_fit.y += style.ScrollbarSize;
if (size_auto_fit_after_constraint.y < size_contents.y && !(window->Flags & ImGuiWindowFlags_NoScrollbar))
size_auto_fit.x += style.ScrollbarSize;
return size_auto_fit;
}
}
ImVec2 ImGui::CalcWindowExpectedSize(ImGuiWindow* window)
{
ImVec2 size_contents = CalcSizeContents(window);
return CalcSizeAfterConstraint(window, CalcSizeAutoFit(window, size_contents));
}
float ImGui::GetWindowScrollMaxX(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.x - (window->SizeFull.x - window->ScrollbarSizes.x));
}
float ImGui::GetWindowScrollMaxY(ImGuiWindow* window)
{
return ImMax(0.0f, window->SizeContents.y - (window->SizeFull.y - window->ScrollbarSizes.y));
}
static ImVec2 CalcNextScrollFromScrollTargetAndClamp(ImGuiWindow* window, bool snap_on_edges)
{
ImGuiContext& g = *GImGui;
ImVec2 scroll = window->Scroll;
if (window->ScrollTarget.x < FLT_MAX)
{
float cr_x = window->ScrollTargetCenterRatio.x;
scroll.x = window->ScrollTarget.x - cr_x * (window->SizeFull.x - window->ScrollbarSizes.x);
}
if (window->ScrollTarget.y < FLT_MAX)
{
// 'snap_on_edges' allows for a discontinuity at the edge of scrolling limits to take account of WindowPadding so that scrolling to make the last item visible scroll far enough to see the padding.
float cr_y = window->ScrollTargetCenterRatio.y;
float target_y = window->ScrollTarget.y;
if (snap_on_edges && cr_y <= 0.0f && target_y <= window->WindowPadding.y)
target_y = 0.0f;
if (snap_on_edges && cr_y >= 1.0f && target_y >= window->SizeContents.y - window->WindowPadding.y + g.Style.ItemSpacing.y)
target_y = window->SizeContents.y;
scroll.y = target_y - (1.0f - cr_y) * (window->TitleBarHeight() + window->MenuBarHeight()) - cr_y * (window->SizeFull.y - window->ScrollbarSizes.y);
}
scroll = ImMax(scroll, ImVec2(0.0f, 0.0f));
if (!window->Collapsed && !window->SkipItems)
{
scroll.x = ImMin(scroll.x, ImGui::GetWindowScrollMaxX(window));
scroll.y = ImMin(scroll.y, ImGui::GetWindowScrollMaxY(window));
}
return scroll;
}
static ImGuiCol GetWindowBgColorIdxFromFlags(ImGuiWindowFlags flags)
{
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
return ImGuiCol_PopupBg;
if (flags & ImGuiWindowFlags_ChildWindow)
return ImGuiCol_ChildBg;
return ImGuiCol_WindowBg;
}
static void CalcResizePosSizeFromAnyCorner(ImGuiWindow* window, const ImVec2& corner_target, const ImVec2& corner_norm, ImVec2* out_pos, ImVec2* out_size)
{
ImVec2 pos_min = ImLerp(corner_target, window->Pos, corner_norm); // Expected window upper-left
ImVec2 pos_max = ImLerp(window->Pos + window->Size, corner_target, corner_norm); // Expected window lower-right
ImVec2 size_expected = pos_max - pos_min;
ImVec2 size_constrained = CalcSizeAfterConstraint(window, size_expected);
*out_pos = pos_min;
if (corner_norm.x == 0.0f)
out_pos->x -= (size_constrained.x - size_expected.x);
if (corner_norm.y == 0.0f)
out_pos->y -= (size_constrained.y - size_expected.y);
*out_size = size_constrained;
}
struct ImGuiResizeGripDef
{
ImVec2 CornerPosN;
ImVec2 InnerDir;
int AngleMin12, AngleMax12;
};
static const ImGuiResizeGripDef resize_grip_def[4] =
{
{ ImVec2(1,1), ImVec2(-1,-1), 0, 3 }, // Lower right
{ ImVec2(0,1), ImVec2(+1,-1), 3, 6 }, // Lower left
{ ImVec2(0,0), ImVec2(+1,+1), 6, 9 }, // Upper left
{ ImVec2(1,0), ImVec2(-1,+1), 9,12 }, // Upper right
};
static ImRect GetResizeBorderRect(ImGuiWindow* window, int border_n, float perp_padding, float thickness)
{
ImRect rect = window->Rect();
if (thickness == 0.0f) rect.Max -= ImVec2(1,1);
if (border_n == 0) return ImRect(rect.Min.x + perp_padding, rect.Min.y - thickness, rect.Max.x - perp_padding, rect.Min.y + thickness); // Top
if (border_n == 1) return ImRect(rect.Max.x - thickness, rect.Min.y + perp_padding, rect.Max.x + thickness, rect.Max.y - perp_padding); // Right
if (border_n == 2) return ImRect(rect.Min.x + perp_padding, rect.Max.y - thickness, rect.Max.x - perp_padding, rect.Max.y + thickness); // Bottom
if (border_n == 3) return ImRect(rect.Min.x - thickness, rect.Min.y + perp_padding, rect.Min.x + thickness, rect.Max.y - perp_padding); // Left
IM_ASSERT(0);
return ImRect();
}
// Handle resize for: Resize Grips, Borders, Gamepad
static void ImGui::UpdateManualResize(ImGuiWindow* window, const ImVec2& size_auto_fit, int* border_held, int resize_grip_count, ImU32 resize_grip_col[4])
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
if ((flags & ImGuiWindowFlags_NoResize) || (flags & ImGuiWindowFlags_AlwaysAutoResize) || window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
return;
if (window->WasActive == false) // Early out to avoid running this code for e.g. an hidden implicit/fallback Debug window.
return;
const int resize_border_count = g.IO.ConfigWindowsResizeFromEdges ? 4 : 0;
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
const float grip_hover_inner_size = (float)(int)(grip_draw_size * 0.75f);
const float grip_hover_outer_size = g.IO.ConfigWindowsResizeFromEdges ? WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS : 0.0f;
ImVec2 pos_target(FLT_MAX, FLT_MAX);
ImVec2 size_target(FLT_MAX, FLT_MAX);
// Manual resize grips
PushID("#RESIZE");
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
// Using the FlattenChilds button flag we make the resize button accessible even if we are hovering over a child window
ImRect resize_rect(corner - grip.InnerDir * grip_hover_outer_size, corner + grip.InnerDir * grip_hover_inner_size);
if (resize_rect.Min.x > resize_rect.Max.x) ImSwap(resize_rect.Min.x, resize_rect.Max.x);
if (resize_rect.Min.y > resize_rect.Max.y) ImSwap(resize_rect.Min.y, resize_rect.Max.y);
bool hovered, held;
ButtonBehavior(resize_rect, window->GetID((void*)(intptr_t)resize_grip_n), &hovered, &held, ImGuiButtonFlags_FlattenChildren | ImGuiButtonFlags_NoNavFocus);
//GetOverlayDrawList(window)->AddRect(resize_rect.Min, resize_rect.Max, IM_COL32(255, 255, 0, 255));
if (hovered || held)
g.MouseCursor = (resize_grip_n & 1) ? ImGuiMouseCursor_ResizeNESW : ImGuiMouseCursor_ResizeNWSE;
if (held && g.IO.MouseDoubleClicked[0] && resize_grip_n == 0)
{
// Manual auto-fit when double-clicking
size_target = CalcSizeAfterConstraint(window, size_auto_fit);
ClearActiveID();
}
else if (held)
{
// Resize from any of the four corners
// We don't use an incremental MouseDelta but rather compute an absolute target size based on mouse position
ImVec2 corner_target = g.IO.MousePos - g.ActiveIdClickOffset + ImLerp(grip.InnerDir * grip_hover_outer_size, grip.InnerDir * -grip_hover_inner_size, grip.CornerPosN); // Corner of the window corresponding to our corner grip
CalcResizePosSizeFromAnyCorner(window, corner_target, grip.CornerPosN, &pos_target, &size_target);
}
if (resize_grip_n == 0 || held || hovered)
resize_grip_col[resize_grip_n] = GetColorU32(held ? ImGuiCol_ResizeGripActive : hovered ? ImGuiCol_ResizeGripHovered : ImGuiCol_ResizeGrip);
}
for (int border_n = 0; border_n < resize_border_count; border_n++)
{
bool hovered, held;
ImRect border_rect = GetResizeBorderRect(window, border_n, grip_hover_inner_size, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS);
ButtonBehavior(border_rect, window->GetID((void*)(intptr_t)(border_n + 4)), &hovered, &held, ImGuiButtonFlags_FlattenChildren);
//GetOverlayDrawList(window)->AddRect(border_rect.Min, border_rect.Max, IM_COL32(255, 255, 0, 255));
if ((hovered && g.HoveredIdTimer > WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER) || held)
{
g.MouseCursor = (border_n & 1) ? ImGuiMouseCursor_ResizeEW : ImGuiMouseCursor_ResizeNS;
if (held)
*border_held = border_n;
}
if (held)
{
ImVec2 border_target = window->Pos;
ImVec2 border_posn;
if (border_n == 0) { border_posn = ImVec2(0, 0); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Top
if (border_n == 1) { border_posn = ImVec2(1, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Right
if (border_n == 2) { border_posn = ImVec2(0, 1); border_target.y = (g.IO.MousePos.y - g.ActiveIdClickOffset.y + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Bottom
if (border_n == 3) { border_posn = ImVec2(0, 0); border_target.x = (g.IO.MousePos.x - g.ActiveIdClickOffset.x + WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS); } // Left
CalcResizePosSizeFromAnyCorner(window, border_target, border_posn, &pos_target, &size_target);
}
}
PopID();
// Navigation resize (keyboard/gamepad)
if (g.NavWindowingTarget && g.NavWindowingTarget->RootWindow == window)
{
ImVec2 nav_resize_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && g.IO.KeyShift)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
nav_resize_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadDPad, ImGuiInputReadMode_Down);
if (nav_resize_delta.x != 0.0f || nav_resize_delta.y != 0.0f)
{
const float NAV_RESIZE_SPEED = 600.0f;
nav_resize_delta *= ImFloor(NAV_RESIZE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y));
g.NavWindowingToggleLayer = false;
g.NavDisableMouseHover = true;
resize_grip_col[0] = GetColorU32(ImGuiCol_ResizeGripActive);
// FIXME-NAV: Should store and accumulate into a separate size buffer to handle sizing constraints properly, right now a constraint will make us stuck.
size_target = CalcSizeAfterConstraint(window, window->SizeFull + nav_resize_delta);
}
}
// Apply back modified position/size to window
if (size_target.x != FLT_MAX)
{
window->SizeFull = size_target;
MarkIniSettingsDirty(window);
}
if (pos_target.x != FLT_MAX)
{
window->Pos = ImFloor(pos_target);
MarkIniSettingsDirty(window);
}
window->Size = window->SizeFull;
}
static inline void ClampWindowRect(ImGuiWindow* window, const ImRect& rect, const ImVec2& padding)
{
ImGuiContext& g = *GImGui;
ImVec2 size_for_clamping = (g.IO.ConfigWindowsMoveFromTitleBarOnly && !(window->Flags & ImGuiWindowFlags_NoTitleBar)) ? ImVec2(window->Size.x, window->TitleBarHeight()) : window->Size;
window->Pos = ImMin(rect.Max - padding, ImMax(window->Pos + size_for_clamping, rect.Min + padding) - size_for_clamping);
}
static void ImGui::RenderOuterBorders(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
float rounding = window->WindowRounding;
float border_size = window->WindowBorderSize;
if (border_size > 0.0f && !(window->Flags & ImGuiWindowFlags_NoBackground))
window->DrawList->AddRect(window->Pos, window->Pos + window->Size, GetColorU32(ImGuiCol_Border), rounding, ImDrawCornerFlags_All, border_size);
int border_held = window->ResizeBorderHeld;
if (border_held != -1)
{
struct ImGuiResizeBorderDef
{
ImVec2 InnerDir;
ImVec2 CornerPosN1, CornerPosN2;
float OuterAngle;
};
static const ImGuiResizeBorderDef resize_border_def[4] =
{
{ ImVec2(0,+1), ImVec2(0,0), ImVec2(1,0), IM_PI*1.50f }, // Top
{ ImVec2(-1,0), ImVec2(1,0), ImVec2(1,1), IM_PI*0.00f }, // Right
{ ImVec2(0,-1), ImVec2(1,1), ImVec2(0,1), IM_PI*0.50f }, // Bottom
{ ImVec2(+1,0), ImVec2(0,1), ImVec2(0,0), IM_PI*1.00f } // Left
};
const ImGuiResizeBorderDef& def = resize_border_def[border_held];
ImRect border_r = GetResizeBorderRect(window, border_held, rounding, 0.0f);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN1) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle - IM_PI*0.25f, def.OuterAngle);
window->DrawList->PathArcTo(ImLerp(border_r.Min, border_r.Max, def.CornerPosN2) + ImVec2(0.5f, 0.5f) + def.InnerDir * rounding, rounding, def.OuterAngle, def.OuterAngle + IM_PI*0.25f);
window->DrawList->PathStroke(GetColorU32(ImGuiCol_SeparatorActive), false, ImMax(2.0f, border_size)); // Thicker than usual
}
if (g.Style.FrameBorderSize > 0 && !(window->Flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
{
float y = window->Pos.y + window->TitleBarHeight() - 1;
window->DrawList->AddLine(ImVec2(window->Pos.x + border_size, y), ImVec2(window->Pos.x + window->Size.x - border_size, y), GetColorU32(ImGuiCol_Border), g.Style.FrameBorderSize);
}
}
void ImGui::UpdateWindowParentAndRootLinks(ImGuiWindow* window, ImGuiWindowFlags flags, ImGuiWindow* parent_window)
{
window->ParentWindow = parent_window;
window->RootWindow = window->RootWindowDockStop = window->RootWindowForTitleBarHighlight = window->RootWindowForNav = window;
if (parent_window && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Tooltip))
{
window->RootWindow = parent_window->RootWindow;
if (!window->DockIsActive && !(parent_window->Flags & ImGuiWindowFlags_DockNodeHost))
window->RootWindowDockStop = parent_window->RootWindowDockStop;
}
if (parent_window && !(flags & ImGuiWindowFlags_Modal) && (flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)))
window->RootWindowForTitleBarHighlight = parent_window->RootWindowForTitleBarHighlight;
while (window->RootWindowForNav->Flags & ImGuiWindowFlags_NavFlattened)
{
IM_ASSERT(window->RootWindowForNav->ParentWindow != NULL);
window->RootWindowForNav = window->RootWindowForNav->ParentWindow;
}
}
// Push a new ImGui window to add widgets to.
// - A default window called "Debug" is automatically stacked at the beginning of every frame so you can use widgets without explicitly calling a Begin/End pair.
// - Begin/End can be called multiple times during the frame with the same window name to append content.
// - The window name is used as a unique identifier to preserve window information across frames (and save rudimentary information to the .ini file).
// You can use the "##" or "###" markers to use the same label with different id, or same id with different label. See documentation at the top of this file.
// - Return false when window is collapsed, so you can early out in your code. You always need to call ImGui::End() even if false is returned.
// - Passing 'bool* p_open' displays a Close button on the upper-right corner of the window, the pointed value will be set to false when the button is pressed.
bool ImGui::Begin(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
const ImGuiStyle& style = g.Style;
IM_ASSERT(name != NULL && name[0] != '\0'); // Window name required
IM_ASSERT(g.FrameScopeActive); // Forgot to call ImGui::NewFrame()
IM_ASSERT(g.FrameCountEnded != g.FrameCount); // Called ImGui::Render() or ImGui::EndFrame() and haven't called ImGui::NewFrame() again yet
// Find or create
ImGuiWindow* window = FindWindowByName(name);
const bool window_just_created = (window == NULL);
const bool window_is_fallback = (g.CurrentWindowStack.Size == 0);
if (window_just_created)
{
ImVec2 size_on_first_use = (g.NextWindowData.SizeCond != 0) ? g.NextWindowData.SizeVal : ImVec2(0.0f, 0.0f); // Any condition flag will do since we are creating a new window here.
window = CreateNewWindow(name, size_on_first_use, flags);
}
// Automatically disable manual moving/resizing when NoInputs is set
if ((flags & ImGuiWindowFlags_NoInputs) == ImGuiWindowFlags_NoInputs)
flags |= ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize;
if (flags & ImGuiWindowFlags_NavFlattened)
IM_ASSERT(flags & ImGuiWindowFlags_ChildWindow);
const int current_frame = g.FrameCount;
const bool first_begin_of_the_frame = (window->LastFrameActive != current_frame);
// Update the Appearing flag
bool window_just_activated_by_user = (window->LastFrameActive < current_frame - 1); // Not using !WasActive because the implicit "Debug" window would always toggle off->on
const bool window_just_appearing_after_hidden_for_resize = (window->HiddenFramesForResize > 0);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
window_just_activated_by_user |= (window->PopupId != popup_ref.PopupId); // We recycle popups so treat window as activated if popup id changed
window_just_activated_by_user |= (window != popup_ref.Window);
}
window->Appearing = (window_just_activated_by_user || window_just_appearing_after_hidden_for_resize);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, true);
// Update Flags, LastFrameActive, BeginOrderXXX fields
if (first_begin_of_the_frame)
{
window->FlagsPreviousFrame = window->Flags;
window->Flags = (ImGuiWindowFlags)flags;
window->LastFrameActive = current_frame;
window->BeginOrderWithinParent = 0;
window->BeginOrderWithinContext = (short)(g.WindowsActiveCount++);
}
else
{
flags = window->Flags;
}
// Docking
// (NB: during the frame dock nodes are created, it is possible that (window->DockIsActive == false) even though (window->DockNode->Windows.Size > 1)
IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL); // Cannot be both
if (g.NextWindowData.DockCond)
SetWindowDock(window, g.NextWindowData.DockId, g.NextWindowData.DockCond);
if (first_begin_of_the_frame)
{
bool has_dock_node = (window->DockId != 0 || window->DockNode != NULL);
bool new_auto_dock_node = !has_dock_node && g.IO.ConfigDockingTabBarOnSingleWindows && !(flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking)) && !window_is_fallback;
if (has_dock_node || new_auto_dock_node)
{
BeginDocked(window, p_open);
flags = window->Flags;
}
}
// Parent window is latched only on the first call to Begin() of the frame, so further append-calls can be done from a different window stack
ImGuiWindow* parent_window_in_stack = window->DockIsActive ? window->DockNode->HostWindow : g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back();
ImGuiWindow* parent_window = first_begin_of_the_frame ? ((flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_Popup)) ? parent_window_in_stack : NULL) : window->ParentWindow;
IM_ASSERT(parent_window != NULL || !(flags & ImGuiWindowFlags_ChildWindow));
// Add to stack
// We intentionally set g.CurrentWindow to NULL to prevent usage until when the viewport is set, then will call SetCurrentWindow()
g.CurrentWindowStack.push_back(window);
g.CurrentWindow = NULL;
CheckStacksSize(window, true);
if (flags & ImGuiWindowFlags_Popup)
{
ImGuiPopupRef& popup_ref = g.OpenPopupStack[g.BeginPopupStack.Size];
popup_ref.Window = window;
g.BeginPopupStack.push_back(popup_ref);
window->PopupId = popup_ref.PopupId;
}
if (window_just_appearing_after_hidden_for_resize && !(flags & ImGuiWindowFlags_ChildWindow))
window->NavLastIds[0] = 0;
// Process SetNextWindow***() calls
bool window_pos_set_by_api = false;
bool window_size_x_set_by_api = false, window_size_y_set_by_api = false;
if (g.NextWindowData.PosCond)
{
window_pos_set_by_api = (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) != 0;
if (window_pos_set_by_api && ImLengthSqr(g.NextWindowData.PosPivotVal) > 0.00001f)
{
// May be processed on the next frame if this is our first frame and we are measuring size
// FIXME: Look into removing the branch so everything can go through this same code path for consistency.
window->SetWindowPosVal = g.NextWindowData.PosVal;
window->SetWindowPosPivot = g.NextWindowData.PosPivotVal;
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
}
else
{
SetWindowPos(window, g.NextWindowData.PosVal, g.NextWindowData.PosCond);
}
}
if (g.NextWindowData.SizeCond)
{
window_size_x_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.x > 0.0f);
window_size_y_set_by_api = (window->SetWindowSizeAllowFlags & g.NextWindowData.SizeCond) != 0 && (g.NextWindowData.SizeVal.y > 0.0f);
SetWindowSize(window, g.NextWindowData.SizeVal, g.NextWindowData.SizeCond);
}
if (g.NextWindowData.ContentSizeCond)
{
// Adjust passed "client size" to become a "window size"
window->SizeContentsExplicit = g.NextWindowData.ContentSizeVal;
if (window->SizeContentsExplicit.y != 0.0f)
window->SizeContentsExplicit.y += window->TitleBarHeight() + window->MenuBarHeight();
}
else if (first_begin_of_the_frame)
{
window->SizeContentsExplicit = ImVec2(0.0f, 0.0f);
}
window->WindowClass = g.NextWindowData.WindowClass;
if (g.NextWindowData.CollapsedCond)
SetWindowCollapsed(window, g.NextWindowData.CollapsedVal, g.NextWindowData.CollapsedCond);
if (g.NextWindowData.FocusCond)
FocusWindow(window);
if (window->Appearing)
SetWindowConditionAllowFlags(window, ImGuiCond_Appearing, false);
// When reusing window again multiple times a frame, just append content (don't need to setup again)
if (first_begin_of_the_frame)
{
// Initialize
const bool window_is_child_tooltip = (flags & ImGuiWindowFlags_ChildWindow) && (flags & ImGuiWindowFlags_Tooltip); // FIXME-WIP: Undocumented behavior of Child+Tooltip for pinned tooltip (#1345)
UpdateWindowParentAndRootLinks(window, flags, parent_window);
window->Active = true;
window->HasCloseButton = (p_open != NULL);
window->ClipRect = ImVec4(-FLT_MAX,-FLT_MAX,+FLT_MAX,+FLT_MAX);
window->IDStack.resize(1);
// Update stored window name when it changes (which can _only_ happen with the "###" operator, so the ID would stay unchanged).
// The title bar always display the 'name' parameter, so we only update the string storage if it needs to be visible to the end-user elsewhere.
bool window_title_visible_elsewhere = false;
if ((window->Viewport && window->Viewport->Window == window) || (window->DockIsActive))
window_title_visible_elsewhere = true;
else if (g.NavWindowingList != NULL && (window->Flags & ImGuiWindowFlags_NoNavFocus) == 0) // Window titles visible when using CTRL+TAB
window_title_visible_elsewhere = true;
if (window_title_visible_elsewhere && !window_just_created && strcmp(name, window->Name) != 0)
{
size_t buf_len = (size_t)window->NameBufLen;
window->Name = ImStrdupcpy(window->Name, &buf_len, name);
window->NameBufLen = (int)buf_len;
}
// UPDATE CONTENTS SIZE, UPDATE HIDDEN STATUS
// Update contents size from last frame for auto-fitting (or use explicit size)
window->SizeContents = CalcSizeContents(window);
if (window->HiddenFramesRegular > 0)
window->HiddenFramesRegular--;
if (window->HiddenFramesForResize > 0)
window->HiddenFramesForResize--;
// Hide new windows for one frame until they calculate their size
if (window_just_created && (!window_size_x_set_by_api || !window_size_y_set_by_api))
window->HiddenFramesForResize = 1;
// Hide popup/tooltip window when re-opening while we measure size (because we recycle the windows)
// We reset Size/SizeContents for reappearing popups/tooltips early in this function, so further code won't be tempted to use the old size.
if (window_just_activated_by_user && (flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) != 0)
{
window->HiddenFramesForResize = 1;
if (flags & ImGuiWindowFlags_AlwaysAutoResize)
{
if (!window_size_x_set_by_api)
window->Size.x = window->SizeFull.x = 0.f;
if (!window_size_y_set_by_api)
window->Size.y = window->SizeFull.y = 0.f;
window->SizeContents = ImVec2(0.f, 0.f);
}
}
// SELECT VIEWPORT
// We need to do this before using any style/font sizes, as viewport with a different DPI may affect font sizes.
UpdateSelectWindowViewport(window);
SetCurrentViewport(window, window->Viewport);
window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
SetCurrentWindow(window);
flags = window->Flags;
// Lock border size and padding for the frame (so that altering them doesn't cause inconsistencies)
if (flags & ImGuiWindowFlags_ChildWindow)
window->WindowBorderSize = style.ChildBorderSize;
else
window->WindowBorderSize = ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupBorderSize : style.WindowBorderSize;
if (!window->DockIsActive && (flags & ImGuiWindowFlags_ChildWindow) && !(flags & (ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_Popup)) && window->WindowBorderSize == 0.0f)
window->WindowPadding = ImVec2(0.0f, (flags & ImGuiWindowFlags_MenuBar) ? style.WindowPadding.y : 0.0f);
else
window->WindowPadding = style.WindowPadding;
window->DC.MenuBarOffset.x = ImMax(ImMax(window->WindowPadding.x, style.ItemSpacing.x), g.NextWindowData.MenuBarOffsetMinVal.x);
window->DC.MenuBarOffset.y = g.NextWindowData.MenuBarOffsetMinVal.y;
// Collapse window by double-clicking on title bar
// At this point we don't have a clipping rectangle setup yet, so we can use the title bar area for hit detection and drawing
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !(flags & ImGuiWindowFlags_NoCollapse) && !window->DockIsActive)
{
// We don't use a regular button+id to test for double-click on title bar (mostly due to legacy reason, could be fixed), so verify that we don't have items over the title bar.
ImRect title_bar_rect = window->TitleBarRect();
if (g.HoveredWindow == window && g.HoveredId == 0 && g.HoveredIdPreviousFrame == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max) && g.IO.MouseDoubleClicked[0])
window->WantCollapseToggle = true;
if (window->WantCollapseToggle)
{
window->Collapsed = !window->Collapsed;
MarkIniSettingsDirty(window);
FocusWindow(window);
}
}
else
{
window->Collapsed = false;
}
window->WantCollapseToggle = false;
// SIZE
// Calculate auto-fit size, handle automatic resize
const ImVec2 size_auto_fit = CalcSizeAutoFit(window, window->SizeContents);
ImVec2 size_full_modified(FLT_MAX, FLT_MAX);
if ((flags & ImGuiWindowFlags_AlwaysAutoResize) && !window->Collapsed)
{
// Using SetNextWindowSize() overrides ImGuiWindowFlags_AlwaysAutoResize, so it can be used on tooltips/popups, etc.
if (!window_size_x_set_by_api)
window->SizeFull.x = size_full_modified.x = size_auto_fit.x;
if (!window_size_y_set_by_api)
window->SizeFull.y = size_full_modified.y = size_auto_fit.y;
}
else if (window->AutoFitFramesX > 0 || window->AutoFitFramesY > 0)
{
// Auto-fit may only grow window during the first few frames
// We still process initial auto-fit on collapsed windows to get a window width, but otherwise don't honor ImGuiWindowFlags_AlwaysAutoResize when collapsed.
if (!window_size_x_set_by_api && window->AutoFitFramesX > 0)
window->SizeFull.x = size_full_modified.x = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.x, size_auto_fit.x) : size_auto_fit.x;
if (!window_size_y_set_by_api && window->AutoFitFramesY > 0)
window->SizeFull.y = size_full_modified.y = window->AutoFitOnlyGrows ? ImMax(window->SizeFull.y, size_auto_fit.y) : size_auto_fit.y;
if (!window->Collapsed)
MarkIniSettingsDirty(window);
}
// Apply minimum/maximum window size constraints and final size
window->SizeFull = CalcSizeAfterConstraint(window, window->SizeFull);
window->Size = window->Collapsed && !(flags & ImGuiWindowFlags_ChildWindow) ? window->TitleBarRect().GetSize() : window->SizeFull;
// SCROLLBAR STATUS
// Update scrollbar status (based on the Size that was effective during last frame or the auto-resized Size).
if (!window->Collapsed)
{
// When reading the current size we need to read it after size constraints have been applied
float size_x_for_scrollbars = size_full_modified.x != FLT_MAX ? window->SizeFull.x : window->SizeFullAtLastBegin.x;
float size_y_for_scrollbars = size_full_modified.y != FLT_MAX ? window->SizeFull.y : window->SizeFullAtLastBegin.y;
window->ScrollbarY = (flags & ImGuiWindowFlags_AlwaysVerticalScrollbar) || ((window->SizeContents.y > size_y_for_scrollbars) && !(flags & ImGuiWindowFlags_NoScrollbar));
window->ScrollbarX = (flags & ImGuiWindowFlags_AlwaysHorizontalScrollbar) || ((window->SizeContents.x > size_x_for_scrollbars - (window->ScrollbarY ? style.ScrollbarSize : 0.0f)) && !(flags & ImGuiWindowFlags_NoScrollbar) && (flags & ImGuiWindowFlags_HorizontalScrollbar));
if (window->ScrollbarX && !window->ScrollbarY)
window->ScrollbarY = (window->SizeContents.y > size_y_for_scrollbars - style.ScrollbarSize) && !(flags & ImGuiWindowFlags_NoScrollbar);
window->ScrollbarSizes = ImVec2(window->ScrollbarY ? style.ScrollbarSize : 0.0f, window->ScrollbarX ? style.ScrollbarSize : 0.0f);
}
// POSITION
// Popup latch its initial position, will position itself when it appears next frame
if (window_just_activated_by_user)
{
window->AutoPosLastDirection = ImGuiDir_None;
if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api)
window->Pos = g.BeginPopupStack.back().OpenPopupPos;
}
// Position child window
if (flags & ImGuiWindowFlags_ChildWindow)
{
IM_ASSERT(parent_window && parent_window->Active);
window->BeginOrderWithinParent = (short)parent_window->DC.ChildWindows.Size;
parent_window->DC.ChildWindows.push_back(window);
if (!(flags & ImGuiWindowFlags_Popup) && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = parent_window->DC.CursorPos;
}
const bool window_pos_with_pivot = (window->SetWindowPosVal.x != FLT_MAX && window->HiddenFramesForResize == 0);
if (window_pos_with_pivot)
SetWindowPos(window, ImMax(style.DisplaySafeAreaPadding, window->SetWindowPosVal - window->SizeFull * window->SetWindowPosPivot), 0); // Position given a pivot (e.g. for centering)
else if ((flags & ImGuiWindowFlags_ChildMenu) != 0)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Popup) != 0 && !window_pos_set_by_api && window_just_appearing_after_hidden_for_resize)
window->Pos = FindBestWindowPosForPopup(window);
else if ((flags & ImGuiWindowFlags_Tooltip) != 0 && !window_pos_set_by_api && !window_is_child_tooltip)
window->Pos = FindBestWindowPosForPopup(window);
// Late create viewport if we don't fit within our current host viewport.
if (window->ViewportAllowPlatformMonitorExtend >= 0 && !window->ViewportOwned && !window->Viewport->PlatformWindowMinimized)
if (!window->Viewport->GetRect().Contains(window->Rect()))
{
// This is based on the assumption that the DPI will be known ahead (same as the DPI of the selection done in UpdateSelectWindowViewport)
//ImGuiViewport* old_viewport = window->Viewport;
window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
// FIXME-DPI
//IM_ASSERT(old_viewport->DpiScale == window->Viewport->DpiScale); // FIXME-DPI: Something went wrong
SetCurrentViewport(window, window->Viewport);
window->FontDpiScale = (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleFonts) ? window->Viewport->DpiScale : 1.0f;
SetCurrentWindow(window);
}
if (window->ViewportOwned)
{
// Synchronize viewport -> window in case the platform window has been moved or resized from the OS/WM
if (window->Viewport->PlatformRequestMove)
window->Pos = window->Viewport->Pos;
if (window->Viewport->PlatformRequestResize)
window->Size = window->SizeFull = window->Viewport->Size;
// Update common viewport flags
ImGuiViewportFlags viewport_flags = (window->Viewport->Flags) & ~(ImGuiViewportFlags_TopMost | ImGuiViewportFlags_NoTaskBarIcon | ImGuiViewportFlags_NoDecoration);
if (flags & ImGuiWindowFlags_Tooltip)
viewport_flags |= ImGuiViewportFlags_TopMost;
if (g.IO.ConfigViewportsNoTaskBarIcon || (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0)
viewport_flags |= ImGuiViewportFlags_NoTaskBarIcon;
if (g.IO.ConfigViewportsNoDecoration || (flags & (ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) != 0)
viewport_flags |= ImGuiViewportFlags_NoDecoration;
if ((viewport_flags & ImGuiViewportFlags_NoDecoration) && (viewport_flags & ImGuiViewportFlags_NoTaskBarIcon))
viewport_flags |= ImGuiViewportFlags_NoFocusOnAppearing | ImGuiViewportFlags_NoFocusOnClick;
// We can overwrite viewport flags using ImGuiWindowClass (advanced users)
// We don't default to the main viewport because.
if (window->WindowClass.ParentViewportId)
window->Viewport->ParentViewportId = window->WindowClass.ParentViewportId;
else
window->Viewport->ParentViewportId = g.IO.ConfigViewportsNoParent ? 0 : IMGUI_VIEWPORT_DEFAULT_ID;
if (window->WindowClass.ViewportFlagsOverrideMask)
viewport_flags = (viewport_flags & ~window->WindowClass.ViewportFlagsOverrideMask) | (window->WindowClass.ViewportFlagsOverrideValue & window->WindowClass.ViewportFlagsOverrideMask);
// We also tell the back-end that clearing the platform window won't be necessary, as our window is filling the viewport and we have disabled BgAlpha
viewport_flags |= ImGuiViewportFlags_NoRendererClear;
window->Viewport->Flags = viewport_flags;
}
// Clamp position so window stays visible within its viewport or monitor
// Ignore zero-sized display explicitly to avoid losing positions if a window manager reports zero-sized window when initializing or minimizing.
ImRect viewport_rect = window->Viewport->GetRect();
if (!window_pos_set_by_api && !(flags & ImGuiWindowFlags_ChildWindow) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
{
ImVec2 clamp_padding = ImMax(style.DisplayWindowPadding, style.DisplaySafeAreaPadding);
if (!window->ViewportOwned && viewport_rect.GetWidth() > 0 && viewport_rect.GetHeight() > 0.0f)
ClampWindowRect(window, viewport_rect, clamp_padding);
else if (window->ViewportOwned && g.PlatformIO.Monitors.Size > 0)
{
if (window->Viewport->PlatformMonitor == -1)
{
// Fallback for "lost" window (e.g. a monitor disconnected): we move the window back over the main viewport
SetWindowPos(window, g.Viewports[0]->Pos + style.DisplayWindowPadding, ImGuiCond_Always);
}
else
{
ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->Viewport->PlatformMonitor];
ClampWindowRect(window, ImRect(monitor.WorkPos, monitor.WorkPos + monitor.WorkSize), clamp_padding);
}
}
}
window->Pos = ImFloor(window->Pos);
// Lock window rounding for the frame (so that altering them doesn't cause inconsistencies)
window->WindowRounding = (flags & ImGuiWindowFlags_ChildWindow) ? style.ChildRounding : ((flags & ImGuiWindowFlags_Popup) && !(flags & ImGuiWindowFlags_Modal)) ? style.PopupRounding : style.WindowRounding;
if (window->ViewportOwned)
window->WindowRounding = 0.0f;
// Prepare for item focus requests
window->FocusIdxAllRequestCurrent = (window->FocusIdxAllRequestNext == INT_MAX || window->FocusIdxAllCounter == -1) ? INT_MAX : (window->FocusIdxAllRequestNext + (window->FocusIdxAllCounter+1)) % (window->FocusIdxAllCounter+1);
window->FocusIdxTabRequestCurrent = (window->FocusIdxTabRequestNext == INT_MAX || window->FocusIdxTabCounter == -1) ? INT_MAX : (window->FocusIdxTabRequestNext + (window->FocusIdxTabCounter+1)) % (window->FocusIdxTabCounter+1);
window->FocusIdxAllCounter = window->FocusIdxTabCounter = -1;
window->FocusIdxAllRequestNext = window->FocusIdxTabRequestNext = INT_MAX;
// Apply scrolling
window->Scroll = CalcNextScrollFromScrollTargetAndClamp(window, true);
window->ScrollTarget = ImVec2(FLT_MAX, FLT_MAX);
// Apply window focus (new and reactivated windows are moved to front)
bool want_focus = false;
if (window_just_activated_by_user && !(flags & ImGuiWindowFlags_NoFocusOnAppearing))
{
if (flags & ImGuiWindowFlags_Popup)
want_focus = true;
else if ((window->DockIsActive || (flags & ImGuiWindowFlags_ChildWindow) == 0) && !(flags & ImGuiWindowFlags_Tooltip))
want_focus = true;
}
// Decide if we are going to handle borders and resize grips
const bool handle_borders_and_resize_grips = (window->DockNodeAsHost || !window->DockIsActive);
// Handle manual resize: Resize Grips, Borders, Gamepad
int border_held = -1;
ImU32 resize_grip_col[4] = { 0 };
const int resize_grip_count = g.IO.ConfigWindowsResizeFromEdges ? 2 : 1; // 4
const float grip_draw_size = (float)(int)ImMax(g.FontSize * 1.35f, window->WindowRounding + 1.0f + g.FontSize * 0.2f);
if (handle_borders_and_resize_grips && !window->Collapsed)
UpdateManualResize(window, size_auto_fit, &border_held, resize_grip_count, &resize_grip_col[0]);
window->ResizeBorderHeld = (signed char)border_held;
// Synchronize window --> viewport
if (window->ViewportOwned)
{
if (!window->Viewport->PlatformRequestMove)
window->Viewport->Pos = window->Pos;
if (!window->Viewport->PlatformRequestResize)
window->Viewport->Size = window->Size;
viewport_rect = window->Viewport->GetRect();
}
// Save last known viewport position within the window itself (so it can be saved in .ini file and restored)
window->ViewportPos = window->Viewport->Pos;
// Default item width. Make it proportional to window size if window manually resizes
if (window->Size.x > 0.0f && !(flags & ImGuiWindowFlags_Tooltip) && !(flags & ImGuiWindowFlags_AlwaysAutoResize))
window->ItemWidthDefault = (float)(int)(window->Size.x * 0.65f);
else
window->ItemWidthDefault = (float)(int)(g.FontSize * 16.0f);
// DRAWING
// Setup draw list and outer clipping rectangle
window->DrawList->Clear();
window->DrawList->Flags = (g.Style.AntiAliasedLines ? ImDrawListFlags_AntiAliasedLines : 0) | (g.Style.AntiAliasedFill ? ImDrawListFlags_AntiAliasedFill : 0);
window->DrawList->PushTextureID(g.Font->ContainerAtlas->TexID);
if ((flags & ImGuiWindowFlags_ChildWindow) && !(flags & ImGuiWindowFlags_Popup) && !window_is_child_tooltip)
PushClipRect(parent_window->ClipRect.Min, parent_window->ClipRect.Max, true);
else
PushClipRect(viewport_rect.Min, viewport_rect.Max, true);
// Draw modal or window list full viewport dimming background (for other viewports we'll render them in EndFrame)
const bool dim_bg_for_modal = (flags & ImGuiWindowFlags_Modal) && window == GetFrontMostPopupModal() && window->HiddenFramesForResize <= 0;
const bool dim_bg_for_window_list = g.NavWindowingTargetAnim && ((window == g.NavWindowingTargetAnim->RootWindow) || (g.NavWindowingList && (window == g.NavWindowingList) && g.NavWindowingList->Viewport != g.NavWindowingTargetAnim->Viewport));
if (dim_bg_for_modal || dim_bg_for_window_list)
{
const ImU32 dim_bg_col = GetColorU32(dim_bg_for_modal ? ImGuiCol_ModalWindowDimBg : ImGuiCol_NavWindowingDimBg, g.DimBgRatio);
window->DrawList->AddRectFilled(viewport_rect.Min, viewport_rect.Max, dim_bg_col);
}
// Draw navigation selection/windowing rectangle background
if (dim_bg_for_window_list && window == g.NavWindowingTargetAnim)
{
ImRect bb = window->Rect();
bb.Expand(g.FontSize);
if (!bb.Contains(viewport_rect)) // Avoid drawing if the window covers all the viewport anyway
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_NavWindowingHighlight, g.NavWindowingHighlightAlpha * 0.25f), g.Style.WindowRounding);
}
// Draw window + handle manual resize
// As we highlight the title bar when want_focus is set, multiple reappearing windows will have have their title bar highlighted on their reappearing frame.
const float window_rounding = window->WindowRounding;
const float window_border_size = window->WindowBorderSize;
const ImGuiWindow* window_to_highlight = g.NavWindowingTarget ? g.NavWindowingTarget : g.NavWindow;
const bool title_bar_is_highlight = want_focus || (window_to_highlight && (window->RootWindowForTitleBarHighlight == window_to_highlight->RootWindowForTitleBarHighlight || (window->DockNode && window->DockNode == window_to_highlight->DockNode)));
const ImRect title_bar_rect = window->TitleBarRect();
if (window->Collapsed)
{
// Title bar only
float backup_border_size = style.FrameBorderSize;
g.Style.FrameBorderSize = window->WindowBorderSize;
ImU32 title_bar_col = GetColorU32((title_bar_is_highlight && !g.NavDisableHighlight) ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBgCollapsed);
RenderFrame(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, true, window_rounding);
g.Style.FrameBorderSize = backup_border_size;
}
else
{
// Window background
if (!(flags & ImGuiWindowFlags_NoBackground))
{
bool is_docking_transparent_payload = false;
if (g.DragDropActive && (g.FrameCount - g.DragDropAcceptFrameCount) <= 1 && g.IO.ConfigDockingTransparentPayload)
if (g.DragDropPayload.IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && *(ImGuiWindow**)g.DragDropPayload.Data == window)
is_docking_transparent_payload = true;
ImU32 bg_col = GetColorU32(GetWindowBgColorIdxFromFlags(flags));
if (window->ViewportOwned)
{
// No alpha
bg_col = (bg_col | IM_COL32_A_MASK);
if (is_docking_transparent_payload)
window->Viewport->Alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
}
else
{
// Adjust alpha. For docking
float alpha = 1.0f;
if (g.NextWindowData.BgAlphaCond != 0)
alpha = g.NextWindowData.BgAlphaVal;
if (is_docking_transparent_payload)
alpha *= DOCKING_TRANSPARENT_PAYLOAD_ALPHA;
if (alpha != 1.0f)
bg_col = (bg_col & ~IM_COL32_A_MASK) | (IM_F32_TO_INT8_SAT(alpha) << IM_COL32_A_SHIFT);
}
window->DrawList->AddRectFilled(window->Pos + ImVec2(0, window->TitleBarHeight()), window->Pos + window->Size, bg_col, window_rounding, (flags & ImGuiWindowFlags_NoTitleBar) ? ImDrawCornerFlags_All : ImDrawCornerFlags_Bot);
}
g.NextWindowData.BgAlphaCond = 0;
// Title bar
// (when docked, DockNode are drawing their own title bar. Individual windows however do NOT set the _NoTitleBar flag,
// in order for their pos/size to be matching their undocking state.)
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
{
ImU32 title_bar_col = GetColorU32(title_bar_is_highlight ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, window_rounding, ImDrawCornerFlags_Top);
}
// Menu bar
if (flags & ImGuiWindowFlags_MenuBar)
{
ImRect menu_bar_rect = window->MenuBarRect();
menu_bar_rect.ClipWith(window->Rect()); // Soft clipping, in particular child window don't have minimum size covering the menu bar so this is useful for them.
window->DrawList->AddRectFilled(menu_bar_rect.Min+ImVec2(window_border_size,0), menu_bar_rect.Max-ImVec2(window_border_size,0), GetColorU32(ImGuiCol_MenuBarBg), (flags & ImGuiWindowFlags_NoTitleBar) ? window_rounding : 0.0f, ImDrawCornerFlags_Top);
if (style.FrameBorderSize > 0.0f && menu_bar_rect.Max.y < window->Pos.y + window->Size.y)
window->DrawList->AddLine(menu_bar_rect.GetBL(), menu_bar_rect.GetBR(), GetColorU32(ImGuiCol_Border), style.FrameBorderSize);
}
// Docking: Unhide tab bar
if (window->DockNode && window->DockNode->IsHiddenTabBar)
{
float unhide_sz_draw = ImFloor(g.FontSize * 0.70f);
float unhide_sz_hit = ImFloor(g.FontSize * 0.55f);
ImVec2 p = window->DockNode->Pos;
ImRect r(p, p + ImVec2(unhide_sz_hit, unhide_sz_hit));
bool hovered, held;
if (ButtonBehavior(r, window->GetID("#UNHIDE"), &hovered, &held, ImGuiButtonFlags_FlattenChildren))
window->DockNode->WantHiddenTabBarToggle = true;
// FIXME-DOCK: Ideally we'd use ImGuiCol_TitleBgActive/ImGuiCol_TitleBg here, but neither is guaranteed to be visible enough at this sort of size..
ImU32 col = GetColorU32(((held && hovered) || (window->DockNode->IsFocused && !hovered)) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button);
window->DrawList->AddTriangleFilled(p, p + ImVec2(unhide_sz_draw, 0.0f), p + ImVec2(0.0f, unhide_sz_draw), col);
}
// Scrollbars
if (window->ScrollbarX)
Scrollbar(ImGuiLayoutType_Horizontal);
if (window->ScrollbarY)
Scrollbar(ImGuiLayoutType_Vertical);
// Render resize grips (after their input handling so we don't have a frame of latency)
if (handle_borders_and_resize_grips && !(flags & ImGuiWindowFlags_NoResize))
{
for (int resize_grip_n = 0; resize_grip_n < resize_grip_count; resize_grip_n++)
{
const ImGuiResizeGripDef& grip = resize_grip_def[resize_grip_n];
const ImVec2 corner = ImLerp(window->Pos, window->Pos + window->Size, grip.CornerPosN);
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(window_border_size, grip_draw_size) : ImVec2(grip_draw_size, window_border_size)));
window->DrawList->PathLineTo(corner + grip.InnerDir * ((resize_grip_n & 1) ? ImVec2(grip_draw_size, window_border_size) : ImVec2(window_border_size, grip_draw_size)));
window->DrawList->PathArcToFast(ImVec2(corner.x + grip.InnerDir.x * (window_rounding + window_border_size), corner.y + grip.InnerDir.y * (window_rounding + window_border_size)), window_rounding, grip.AngleMin12, grip.AngleMax12);
window->DrawList->PathFillConvex(resize_grip_col[resize_grip_n]);
}
}
// Borders (for dock node host they will be rendered over after the tab bar)
if (handle_borders_and_resize_grips && !window->DockNodeAsHost)
RenderOuterBorders(window);
}
// Store a backup of SizeFull which we will use next frame to decide if we need scrollbars.
window->SizeFullAtLastBegin = window->SizeFull;
// Update various regions. Variables they depends on are set above in this function.
// FIXME: window->ContentsRegionRect.Max is currently very misleading / partly faulty, but some BeginChild() patterns relies on it.
window->ContentsRegionRect.Min.x = window->Pos.x - window->Scroll.x + window->WindowPadding.x;
window->ContentsRegionRect.Min.y = window->Pos.y - window->Scroll.y + window->WindowPadding.y + window->TitleBarHeight() + window->MenuBarHeight();
window->ContentsRegionRect.Max.x = window->Pos.x - window->Scroll.x - window->WindowPadding.x + (window->SizeContentsExplicit.x != 0.0f ? window->SizeContentsExplicit.x : (window->Size.x - window->ScrollbarSizes.x));
window->ContentsRegionRect.Max.y = window->Pos.y - window->Scroll.y - window->WindowPadding.y + (window->SizeContentsExplicit.y != 0.0f ? window->SizeContentsExplicit.y : (window->Size.y - window->ScrollbarSizes.y));
// Setup drawing context
// (NB: That term "drawing context / DC" lost its meaning a long time ago. Initially was meant to hold transient data only. Nowadays difference between window-> and window->DC-> is dubious.)
window->DC.Indent.x = 0.0f + window->WindowPadding.x - window->Scroll.x;
window->DC.GroupOffset.x = 0.0f;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorStartPos = window->Pos + ImVec2(window->DC.Indent.x + window->DC.ColumnsOffset.x, window->TitleBarHeight() + window->MenuBarHeight() + window->WindowPadding.y - window->Scroll.y);
window->DC.CursorPos = window->DC.CursorStartPos;
window->DC.CursorPosPrevLine = window->DC.CursorPos;
window->DC.CursorMaxPos = window->DC.CursorStartPos;
window->DC.CurrentLineSize = window->DC.PrevLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset = 0.0f;
window->DC.NavHideHighlightOneFrame = false;
window->DC.NavHasScroll = (GetWindowScrollMaxY(window) > 0.0f);
window->DC.NavLayerActiveMask = window->DC.NavLayerActiveMaskNext;
window->DC.NavLayerActiveMaskNext = 0x00;
window->DC.MenuBarAppending = false;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f;
window->DC.ChildWindows.resize(0);
window->DC.LayoutType = ImGuiLayoutType_Vertical;
window->DC.ParentLayoutType = parent_window ? parent_window->DC.LayoutType : ImGuiLayoutType_Vertical;
window->DC.ItemFlags = parent_window ? parent_window->DC.ItemFlags : ImGuiItemFlags_Default_;
window->DC.ItemWidth = window->ItemWidthDefault;
window->DC.TextWrapPos = -1.0f; // disabled
window->DC.ItemFlagsStack.resize(0);
window->DC.ItemWidthStack.resize(0);
window->DC.TextWrapPosStack.resize(0);
window->DC.ColumnsSet = NULL;
window->DC.TreeDepth = 0;
window->DC.TreeDepthMayJumpToParentOnPop = 0x00;
window->DC.StateStorage = &window->StateStorage;
window->DC.GroupStack.resize(0);
window->MenuColumns.Update(3, style.ItemSpacing.x, window_just_activated_by_user);
if ((flags & ImGuiWindowFlags_ChildWindow) && (window->DC.ItemFlags != parent_window->DC.ItemFlags))
{
window->DC.ItemFlags = parent_window->DC.ItemFlags;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
if (window->AutoFitFramesX > 0)
window->AutoFitFramesX--;
if (window->AutoFitFramesY > 0)
window->AutoFitFramesY--;
// Apply focus (we need to call FocusWindow() AFTER setting DC.CursorStartPos so our initial navigation reference rectangle can start around there)
if (want_focus)
{
FocusWindow(window);
NavInitWindow(window, false);
}
// Close from platform window
if (p_open != NULL && window->Viewport->PlatformRequestClose && window->Viewport != GetMainViewport())
{
if (!window->DockIsActive || window->DockTabIsVisible)
{
window->Viewport->PlatformRequestClose = false;
g.NavWindowingToggleLayer = false; // Assume user mapped PlatformRequestClose on ALT-F4 so we disable ALT for menu toggle. False positive not an issue.
//IMGUI_DEBUG_LOG("Window '%s' PlatformRequestClose\n", window->Name);
*p_open = false;
}
}
// Title bar
if (!(flags & ImGuiWindowFlags_NoTitleBar) && !window->DockIsActive)
{
// Close & collapse button are on layer 1 (same as menus) and don't default focus
const ImGuiItemFlags item_flags_backup = window->DC.ItemFlags;
window->DC.ItemFlags |= ImGuiItemFlags_NoNavDefaultFocus;
window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
// Collapse button
if (!(flags & ImGuiWindowFlags_NoCollapse))
if (CollapseButton(window->GetID("#COLLAPSE"), window->Pos, NULL))
window->WantCollapseToggle = true; // Defer collapsing to next frame as we are too far in the Begin() function
// Close button
if (p_open != NULL)
{
const float rad = g.FontSize * 0.5f;
if (CloseButton(window->GetID("#CLOSE"), ImVec2(window->Pos.x + window->Size.x - style.FramePadding.x - rad, window->Pos.y + style.FramePadding.y + rad), rad + 1))
*p_open = false;
}
window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
window->DC.ItemFlags = item_flags_backup;
// Title bar text (with: horizontal alignment, avoiding collapse/close button, optional "unsaved document" marker)
// FIXME: Refactor text alignment facilities along with RenderText helpers, this is too much code..
const char* UNSAVED_DOCUMENT_MARKER = "*";
float marker_size_x = (flags & ImGuiWindowFlags_UnsavedDocument) ? CalcTextSize(UNSAVED_DOCUMENT_MARKER, NULL, false).x : 0.0f;
ImVec2 text_size = CalcTextSize(name, NULL, true) + ImVec2(marker_size_x, 0.0f);
ImRect text_r = title_bar_rect;
float pad_left = (flags & ImGuiWindowFlags_NoCollapse) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
float pad_right = (p_open == NULL) ? style.FramePadding.x : (style.FramePadding.x + g.FontSize + style.ItemInnerSpacing.x);
if (style.WindowTitleAlign.x > 0.0f)
pad_right = ImLerp(pad_right, pad_left, style.WindowTitleAlign.x);
text_r.Min.x += pad_left;
text_r.Max.x -= pad_right;
ImRect clip_rect = text_r;
clip_rect.Max.x = window->Pos.x + window->Size.x - (p_open ? title_bar_rect.GetHeight() - 3 : style.FramePadding.x); // Match the size of CloseButton()
RenderTextClipped(text_r.Min, text_r.Max, name, NULL, &text_size, style.WindowTitleAlign, &clip_rect);
if (flags & ImGuiWindowFlags_UnsavedDocument)
{
ImVec2 marker_pos = ImVec2(ImMax(text_r.Min.x, text_r.Min.x + (text_r.GetWidth() - text_size.x) * style.WindowTitleAlign.x) + text_size.x, text_r.Min.y) + ImVec2(2 - marker_size_x, 0.0f);
ImVec2 off = ImVec2(0.0f, (float)(int)(-g.FontSize * 0.25f));
RenderTextClipped(marker_pos + off, text_r.Max + off, UNSAVED_DOCUMENT_MARKER, NULL, NULL, ImVec2(0, style.WindowTitleAlign.y), &clip_rect);
}
}
// Clear hit test shape every frame
window->HitTestHoleSize.x = window->HitTestHoleSize.y = 0;
// Save clipped aabb so we can access it in constant-time in FindHoveredWindow()
window->OuterRectClipped = window->Rect();
if (window->DockIsActive)
window->OuterRectClipped.Min.y += window->TitleBarHeight();
window->OuterRectClipped.ClipWith(window->ClipRect);
// Pressing CTRL+C while holding on a window copy its content to the clipboard
// This works but 1. doesn't handle multiple Begin/End pairs, 2. recursing into another Begin/End pair - so we need to work that out and add better logging scope.
// Maybe we can support CTRL+C on every element?
/*
if (g.ActiveId == move_id)
if (g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_C))
LogToClipboard();
*/
// Inner rectangle
// We set this up after processing the resize grip so that our clip rectangle doesn't lag by a frame
// Note that if our window is collapsed we will end up with an inverted (~null) clipping rectangle which is the correct behavior.
window->InnerMainRect.Min.x = title_bar_rect.Min.x + window->WindowBorderSize;
window->InnerMainRect.Min.y = title_bar_rect.Max.y + window->MenuBarHeight() + (((flags & ImGuiWindowFlags_MenuBar) || !(flags & ImGuiWindowFlags_NoTitleBar)) ? style.FrameBorderSize : window->WindowBorderSize);
window->InnerMainRect.Max.x = window->Pos.x + window->Size.x - window->ScrollbarSizes.x - window->WindowBorderSize;
window->InnerMainRect.Max.y = window->Pos.y + window->Size.y - window->ScrollbarSizes.y - window->WindowBorderSize;
//window->DrawList->AddRect(window->InnerRect.Min, window->InnerRect.Max, IM_COL32_WHITE);
// Inner clipping rectangle
// Force round operator last to ensure that e.g. (int)(max.x-min.x) in user's render code produce correct result.
window->InnerClipRect.Min.x = ImFloor(0.5f + window->InnerMainRect.Min.x + ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
window->InnerClipRect.Min.y = ImFloor(0.5f + window->InnerMainRect.Min.y);
window->InnerClipRect.Max.x = ImFloor(0.5f + window->InnerMainRect.Max.x - ImMax(0.0f, ImFloor(window->WindowPadding.x*0.5f - window->WindowBorderSize)));
window->InnerClipRect.Max.y = ImFloor(0.5f + window->InnerMainRect.Max.y);
if (g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable)
{
// Docking: Dragging a dockable window (or any of its child) turns it into a drag and drop source.
// We need to do this _before_ we overwrite window->DC.LastItemId below because BeginAsDockableDragDropSource() also overwrites it.
if ((g.ActiveId == window->MoveId) && ((g.IO.ConfigDockingWithShift && g.IO.KeyShift) || (!g.IO.ConfigDockingWithShift)))
if ((window->Flags & ImGuiWindowFlags_NoMove) == 0)
if ((window->RootWindow->Flags & (ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking)) == 0)
BeginAsDockableDragDropSource(window);
// Docking: Any dockable window can act as a target. For dock node hosts we call BeginAsDockableDragDropTarget() in DockNodeUpdate() instead.
if (g.DragDropActive && !(flags & ImGuiWindowFlags_NoDocking))
if (g.MovingWindow == NULL || g.MovingWindow->RootWindow != window)
if ((window == window->RootWindow) && !(window->Flags & ImGuiWindowFlags_DockNodeHost))
BeginAsDockableDragDropTarget(window);
}
// We fill last item data based on Title Bar or Tab, in order for IsItemHovered() and IsItemActive() to be usable after Begin().
// This is useful to allow creating context menus on title bar only, etc.
if (window->DockIsActive)
{
window->DC.LastItemId = window->ID;
window->DC.LastItemStatusFlags = window->DockTabItemStatusFlags;
window->DC.LastItemRect = window->DockTabItemRect;
}
else
{
window->DC.LastItemId = window->MoveId;
window->DC.LastItemStatusFlags = IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max, false) ? ImGuiItemStatusFlags_HoveredRect : 0;
window->DC.LastItemRect = title_bar_rect;
}
}
else
{
// Append
SetCurrentViewport(window, window->Viewport);
SetCurrentWindow(window);
}
if (!(flags & ImGuiWindowFlags_DockNodeHost))
PushClipRect(window->InnerClipRect.Min, window->InnerClipRect.Max, true);
// Clear 'accessed' flag last thing (After PushClipRect which will set the flag. We want the flag to stay false when the default "Debug" window is unused)
if (first_begin_of_the_frame)
window->WriteAccessed = false;
window->BeginCount++;
g.NextWindowData.Clear();
if (window->DockIsActive && !window->DockTabIsVisible)
window->HiddenFramesRegular = 1;
if (flags & ImGuiWindowFlags_ChildWindow)
{
// Child window can be out of sight and have "negative" clip windows.
// Mark them as collapsed so commands are skipped earlier (we can't manually collapse them because they have no title bar).
IM_ASSERT((flags & ImGuiWindowFlags_NoTitleBar) != 0 || (window->DockIsActive));
if (!(flags & ImGuiWindowFlags_AlwaysAutoResize) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0)
if (window->OuterRectClipped.Min.x >= window->OuterRectClipped.Max.x || window->OuterRectClipped.Min.y >= window->OuterRectClipped.Max.y)
window->HiddenFramesRegular = 1;
// Completely hide along with parent or if parent is collapsed
if (parent_window && (parent_window->Collapsed || parent_window->Hidden))
window->HiddenFramesRegular = 1;
}
// Don't render if style alpha is 0.0 at the time of Begin(). This is arbitrary and inconsistent but has been there for a long while (may remove at some point)
if (style.Alpha <= 0.0f)
window->HiddenFramesRegular = 1;
// Update the Hidden flag
window->Hidden = (window->HiddenFramesRegular > 0) || (window->HiddenFramesForResize > 0);
// Return false if we don't intend to display anything to allow user to perform an early out optimization
window->SkipItems = (window->Collapsed || !window->Active || window->Hidden) && window->AutoFitFramesX <= 0 && window->AutoFitFramesY <= 0 && window->HiddenFramesForResize <= 0;
return !window->SkipItems;
}
// Old Begin() API with 5 parameters, avoid calling this version directly! Use SetNextWindowSize()/SetNextWindowBgAlpha() + Begin() instead.
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
bool ImGui::Begin(const char* name, bool* p_open, const ImVec2& size_first_use, float bg_alpha_override, ImGuiWindowFlags flags)
{
// Old API feature: we could pass the initial window size as a parameter. This was misleading because it only had an effect if the window didn't have data in the .ini file.
if (size_first_use.x != 0.0f || size_first_use.y != 0.0f)
SetNextWindowSize(size_first_use, ImGuiCond_FirstUseEver);
// Old API feature: override the window background alpha with a parameter.
if (bg_alpha_override >= 0.0f)
SetNextWindowBgAlpha(bg_alpha_override);
return Begin(name, p_open, flags);
}
#endif // IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::End()
{
ImGuiContext& g = *GImGui;
if (g.CurrentWindowStack.Size <= 1 && g.FrameScopePushedImplicitWindow)
{
IM_ASSERT(g.CurrentWindowStack.Size > 1 && "Calling End() too many times!");
return; // FIXME-ERRORHANDLING
}
IM_ASSERT(g.CurrentWindowStack.Size > 0);
ImGuiWindow* window = g.CurrentWindow;
if (window->DC.ColumnsSet != NULL)
EndColumns();
if (!(window->Flags & ImGuiWindowFlags_DockNodeHost)) // Pop inner window clip rectangle
PopClipRect();
// Stop logging
if (!(window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME: add more options for scope of logging
LogFinish();
// Docking: report contents sizes to parent to allow for auto-resize
if (window->DockNode && window->DockTabIsVisible)
if (ImGuiWindow* host_window = window->DockNode->HostWindow) // FIXME-DOCK
host_window->DC.CursorMaxPos = window->DC.CursorMaxPos + window->WindowPadding - host_window->WindowPadding;
// Pop from window stack
g.CurrentWindowStack.pop_back();
if (window->Flags & ImGuiWindowFlags_Popup)
g.BeginPopupStack.pop_back();
CheckStacksSize(window, false);
SetCurrentWindow(g.CurrentWindowStack.empty() ? NULL : g.CurrentWindowStack.back());
if (g.CurrentWindow)
SetCurrentViewport(g.CurrentWindow, g.CurrentWindow->Viewport);
}
void ImGui::BringWindowToFocusFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.WindowsFocusOrder.back() == window)
return;
for (int i = g.WindowsFocusOrder.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.WindowsFocusOrder[i] == window)
{
memmove(&g.WindowsFocusOrder[i], &g.WindowsFocusOrder[i + 1], (size_t)(g.WindowsFocusOrder.Size - i - 1) * sizeof(ImGuiWindow*));
g.WindowsFocusOrder[g.WindowsFocusOrder.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayFront(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* current_front_window = g.Windows.back();
if (current_front_window == window || current_front_window->RootWindow == window)
return;
for (int i = g.Windows.Size - 2; i >= 0; i--) // We can ignore the front most window
if (g.Windows[i] == window)
{
memmove(&g.Windows[i], &g.Windows[i + 1], (size_t)(g.Windows.Size - i - 1) * sizeof(ImGuiWindow*));
g.Windows[g.Windows.Size - 1] = window;
break;
}
}
void ImGui::BringWindowToDisplayBack(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.Windows[0] == window)
return;
for (int i = 0; i < g.Windows.Size; i++)
if (g.Windows[i] == window)
{
memmove(&g.Windows[1], &g.Windows[0], (size_t)i * sizeof(ImGuiWindow*));
g.Windows[0] = window;
break;
}
}
// Moving window to front of display and set focus (which happens to be back of our sorted list)
void ImGui::FocusWindow(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window)
{
g.NavWindow = window;
if (window && g.NavDisableMouseHover)
g.NavMousePosDirty = true;
g.NavInitRequest = false;
g.NavId = window ? window->NavLastIds[0] : 0; // Restore NavId
g.NavIdIsAlive = false;
g.NavLayer = ImGuiNavLayer_Main;
//IMGUI_DEBUG_LOG("FocusWindow(\"%s\")\n", window ? window->Name : NULL);
}
// Passing NULL allow to disable keyboard focus
if (!window)
return;
// Select in dock node
if (window->DockNode && window->DockNode->TabBar)
window->DockNode->TabBar->SelectedTabId = window->DockNode->TabBar->NextSelectedTabId = window->ID;
// Move the root window to the top of the pile
if (window->RootWindow)
window = window->RootWindow;
// Steal focus on active widgets
if (window->Flags & ImGuiWindowFlags_Popup) // FIXME: This statement should be unnecessary. Need further testing before removing it..
if (g.ActiveId != 0 && g.ActiveIdWindow && g.ActiveIdWindow->RootWindow != window)
ClearActiveID();
// Bring to front
BringWindowToFocusFront(window);
if (!(window->Flags & ImGuiWindowFlags_NoBringToFrontOnFocus))
BringWindowToDisplayFront(window);
}
void ImGui::FocusPreviousWindowIgnoringOne(ImGuiWindow* ignore_window)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size - 1; i >= 0; i--)
{
// We may later decide to test for different NoXXXInputs based on the active navigation input (mouse vs nav) but that may feel more confusing to the user.
ImGuiWindow* window = g.WindowsFocusOrder[i];
if (window != ignore_window && window->WasActive && !(window->Flags & ImGuiWindowFlags_ChildWindow))
if ((window->Flags & (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs)) != (ImGuiWindowFlags_NoMouseInputs | ImGuiWindowFlags_NoNavInputs))
{
ImGuiWindow* focus_window = NavRestoreLastChildNavWindow(window);
FocusWindow(focus_window);
return;
}
}
}
void ImGui::PushItemWidth(float item_width)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidth = (item_width == 0.0f ? window->ItemWidthDefault : item_width);
window->DC.ItemWidthStack.push_back(window->DC.ItemWidth);
}
void ImGui::PushMultiItemsWidths(int components, float w_full)
{
ImGuiWindow* window = GetCurrentWindow();
const ImGuiStyle& style = GImGui->Style;
if (w_full <= 0.0f)
w_full = CalcItemWidth();
const float w_item_one = ImMax(1.0f, (float)(int)((w_full - (style.ItemInnerSpacing.x) * (components-1)) / (float)components));
const float w_item_last = ImMax(1.0f, (float)(int)(w_full - (w_item_one + style.ItemInnerSpacing.x) * (components-1)));
window->DC.ItemWidthStack.push_back(w_item_last);
for (int i = 0; i < components-1; i++)
window->DC.ItemWidthStack.push_back(w_item_one);
window->DC.ItemWidth = window->DC.ItemWidthStack.back();
}
void ImGui::PopItemWidth()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemWidthStack.pop_back();
window->DC.ItemWidth = window->DC.ItemWidthStack.empty() ? window->ItemWidthDefault : window->DC.ItemWidthStack.back();
}
float ImGui::CalcItemWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
float w = window->DC.ItemWidth;
if (w < 0.0f)
{
// Align to a right-side limit. We include 1 frame padding in the calculation because this is how the width is always used (we add 2 frame padding to it), but we could move that responsibility to the widget as well.
float width_to_right_edge = GetContentRegionAvail().x;
w = ImMax(1.0f, width_to_right_edge + w);
}
w = (float)(int)w;
return w;
}
void ImGui::SetCurrentFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(font && font->IsLoaded()); // Font Atlas not created. Did you call io.Fonts->GetTexDataAsRGBA32 / GetTexDataAsAlpha8 ?
IM_ASSERT(font->Scale > 0.0f);
g.Font = font;
g.FontBaseSize = ImMax(1.0f, g.IO.FontGlobalScale * g.Font->FontSize * g.Font->Scale);
g.FontSize = g.CurrentWindow ? g.CurrentWindow->CalcFontSize() : 0.0f;
ImFontAtlas* atlas = g.Font->ContainerAtlas;
g.DrawListSharedData.TexUvWhitePixel = atlas->TexUvWhitePixel;
g.DrawListSharedData.Font = g.Font;
g.DrawListSharedData.FontSize = g.FontSize;
}
void ImGui::PushFont(ImFont* font)
{
ImGuiContext& g = *GImGui;
if (!font)
font = GetDefaultFont();
SetCurrentFont(font);
g.FontStack.push_back(font);
g.CurrentWindow->DrawList->PushTextureID(font->ContainerAtlas->TexID);
}
void ImGui::PopFont()
{
ImGuiContext& g = *GImGui;
g.CurrentWindow->DrawList->PopTextureID();
g.FontStack.pop_back();
SetCurrentFont(g.FontStack.empty() ? GetDefaultFont() : g.FontStack.back());
}
void ImGui::PushItemFlag(ImGuiItemFlags option, bool enabled)
{
ImGuiWindow* window = GetCurrentWindow();
if (enabled)
window->DC.ItemFlags |= option;
else
window->DC.ItemFlags &= ~option;
window->DC.ItemFlagsStack.push_back(window->DC.ItemFlags);
}
void ImGui::PopItemFlag()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.ItemFlagsStack.pop_back();
window->DC.ItemFlags = window->DC.ItemFlagsStack.empty() ? ImGuiItemFlags_Default_ : window->DC.ItemFlagsStack.back();
}
// FIXME: Look into renaming this once we have settled the new Focus/Activation/TabStop system.
void ImGui::PushAllowKeyboardFocus(bool allow_keyboard_focus)
{
PushItemFlag(ImGuiItemFlags_NoTabStop, !allow_keyboard_focus);
}
void ImGui::PopAllowKeyboardFocus()
{
PopItemFlag();
}
void ImGui::PushButtonRepeat(bool repeat)
{
PushItemFlag(ImGuiItemFlags_ButtonRepeat, repeat);
}
void ImGui::PopButtonRepeat()
{
PopItemFlag();
}
void ImGui::PushTextWrapPos(float wrap_pos_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPos = wrap_pos_x;
window->DC.TextWrapPosStack.push_back(wrap_pos_x);
}
void ImGui::PopTextWrapPos()
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.TextWrapPosStack.pop_back();
window->DC.TextWrapPos = window->DC.TextWrapPosStack.empty() ? -1.0f : window->DC.TextWrapPosStack.back();
}
// FIXME: This may incur a round-trip (if the end user got their data from a float4) but eventually we aim to store the in-flight colors as ImU32
void ImGui::PushStyleColor(ImGuiCol idx, ImU32 col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = ColorConvertU32ToFloat4(col);
}
void ImGui::PushStyleColor(ImGuiCol idx, const ImVec4& col)
{
ImGuiContext& g = *GImGui;
ImGuiColorMod backup;
backup.Col = idx;
backup.BackupValue = g.Style.Colors[idx];
g.ColorModifiers.push_back(backup);
g.Style.Colors[idx] = col;
}
void ImGui::PopStyleColor(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
ImGuiColorMod& backup = g.ColorModifiers.back();
g.Style.Colors[backup.Col] = backup.BackupValue;
g.ColorModifiers.pop_back();
count--;
}
}
struct ImGuiStyleVarInfo
{
ImGuiDataType Type;
ImU32 Count;
ImU32 Offset;
void* GetVarPtr(ImGuiStyle* style) const { return (void*)((unsigned char*)style + Offset); }
};
static const ImGuiStyleVarInfo GStyleVarInfo[] =
{
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, Alpha) }, // ImGuiStyleVar_Alpha
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowPadding) }, // ImGuiStyleVar_WindowPadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowRounding) }, // ImGuiStyleVar_WindowRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowBorderSize) }, // ImGuiStyleVar_WindowBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowMinSize) }, // ImGuiStyleVar_WindowMinSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, WindowTitleAlign) }, // ImGuiStyleVar_WindowTitleAlign
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildRounding) }, // ImGuiStyleVar_ChildRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ChildBorderSize) }, // ImGuiStyleVar_ChildBorderSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupRounding) }, // ImGuiStyleVar_PopupRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, PopupBorderSize) }, // ImGuiStyleVar_PopupBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, FramePadding) }, // ImGuiStyleVar_FramePadding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameRounding) }, // ImGuiStyleVar_FrameRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, FrameBorderSize) }, // ImGuiStyleVar_FrameBorderSize
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemSpacing) }, // ImGuiStyleVar_ItemSpacing
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ItemInnerSpacing) }, // ImGuiStyleVar_ItemInnerSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, IndentSpacing) }, // ImGuiStyleVar_IndentSpacing
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarSize) }, // ImGuiStyleVar_ScrollbarSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, ScrollbarRounding) }, // ImGuiStyleVar_ScrollbarRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabMinSize) }, // ImGuiStyleVar_GrabMinSize
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, GrabRounding) }, // ImGuiStyleVar_GrabRounding
{ ImGuiDataType_Float, 1, (ImU32)IM_OFFSETOF(ImGuiStyle, TabRounding) }, // ImGuiStyleVar_TabRounding
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, ButtonTextAlign) }, // ImGuiStyleVar_ButtonTextAlign
{ ImGuiDataType_Float, 2, (ImU32)IM_OFFSETOF(ImGuiStyle, SelectableTextAlign) }, // ImGuiStyleVar_SelectableTextAlign
};
static const ImGuiStyleVarInfo* GetStyleVarInfo(ImGuiStyleVar idx)
{
IM_ASSERT(idx >= 0 && idx < ImGuiStyleVar_COUNT);
IM_ASSERT(IM_ARRAYSIZE(GStyleVarInfo) == ImGuiStyleVar_COUNT);
return &GStyleVarInfo[idx];
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, float val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 1)
{
ImGuiContext& g = *GImGui;
float* pvar = (float*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0); // Called function with wrong-type? Variable is not a float.
}
void ImGui::PushStyleVar(ImGuiStyleVar idx, const ImVec2& val)
{
const ImGuiStyleVarInfo* var_info = GetStyleVarInfo(idx);
if (var_info->Type == ImGuiDataType_Float && var_info->Count == 2)
{
ImGuiContext& g = *GImGui;
ImVec2* pvar = (ImVec2*)var_info->GetVarPtr(&g.Style);
g.StyleModifiers.push_back(ImGuiStyleMod(idx, *pvar));
*pvar = val;
return;
}
IM_ASSERT(0); // Called function with wrong-type? Variable is not a ImVec2.
}
void ImGui::PopStyleVar(int count)
{
ImGuiContext& g = *GImGui;
while (count > 0)
{
// We avoid a generic memcpy(data, &backup.Backup.., GDataTypeSize[info->Type] * info->Count), the overhead in Debug is not worth it.
ImGuiStyleMod& backup = g.StyleModifiers.back();
const ImGuiStyleVarInfo* info = GetStyleVarInfo(backup.VarIdx);
void* data = info->GetVarPtr(&g.Style);
if (info->Type == ImGuiDataType_Float && info->Count == 1) { ((float*)data)[0] = backup.BackupFloat[0]; }
else if (info->Type == ImGuiDataType_Float && info->Count == 2) { ((float*)data)[0] = backup.BackupFloat[0]; ((float*)data)[1] = backup.BackupFloat[1]; }
g.StyleModifiers.pop_back();
count--;
}
}
const char* ImGui::GetStyleColorName(ImGuiCol idx)
{
// Create switch-case from enum with regexp: ImGuiCol_{.*}, --> case ImGuiCol_\1: return "\1";
switch (idx)
{
case ImGuiCol_Text: return "Text";
case ImGuiCol_TextDisabled: return "TextDisabled";
case ImGuiCol_WindowBg: return "WindowBg";
case ImGuiCol_ChildBg: return "ChildBg";
case ImGuiCol_PopupBg: return "PopupBg";
case ImGuiCol_Border: return "Border";
case ImGuiCol_BorderShadow: return "BorderShadow";
case ImGuiCol_FrameBg: return "FrameBg";
case ImGuiCol_FrameBgHovered: return "FrameBgHovered";
case ImGuiCol_FrameBgActive: return "FrameBgActive";
case ImGuiCol_TitleBg: return "TitleBg";
case ImGuiCol_TitleBgActive: return "TitleBgActive";
case ImGuiCol_TitleBgCollapsed: return "TitleBgCollapsed";
case ImGuiCol_MenuBarBg: return "MenuBarBg";
case ImGuiCol_ScrollbarBg: return "ScrollbarBg";
case ImGuiCol_ScrollbarGrab: return "ScrollbarGrab";
case ImGuiCol_ScrollbarGrabHovered: return "ScrollbarGrabHovered";
case ImGuiCol_ScrollbarGrabActive: return "ScrollbarGrabActive";
case ImGuiCol_CheckMark: return "CheckMark";
case ImGuiCol_SliderGrab: return "SliderGrab";
case ImGuiCol_SliderGrabActive: return "SliderGrabActive";
case ImGuiCol_Button: return "Button";
case ImGuiCol_ButtonHovered: return "ButtonHovered";
case ImGuiCol_ButtonActive: return "ButtonActive";
case ImGuiCol_Header: return "Header";
case ImGuiCol_HeaderHovered: return "HeaderHovered";
case ImGuiCol_HeaderActive: return "HeaderActive";
case ImGuiCol_Separator: return "Separator";
case ImGuiCol_SeparatorHovered: return "SeparatorHovered";
case ImGuiCol_SeparatorActive: return "SeparatorActive";
case ImGuiCol_ResizeGrip: return "ResizeGrip";
case ImGuiCol_ResizeGripHovered: return "ResizeGripHovered";
case ImGuiCol_ResizeGripActive: return "ResizeGripActive";
case ImGuiCol_Tab: return "Tab";
case ImGuiCol_TabHovered: return "TabHovered";
case ImGuiCol_TabActive: return "TabActive";
case ImGuiCol_TabUnfocused: return "TabUnfocused";
case ImGuiCol_TabUnfocusedActive: return "TabUnfocusedActive";
case ImGuiCol_DockingPreview: return "DockingPreview";
case ImGuiCol_DockingEmptyBg: return "DockingEmptyBg";
case ImGuiCol_PlotLines: return "PlotLines";
case ImGuiCol_PlotLinesHovered: return "PlotLinesHovered";
case ImGuiCol_PlotHistogram: return "PlotHistogram";
case ImGuiCol_PlotHistogramHovered: return "PlotHistogramHovered";
case ImGuiCol_TextSelectedBg: return "TextSelectedBg";
case ImGuiCol_DragDropTarget: return "DragDropTarget";
case ImGuiCol_NavHighlight: return "NavHighlight";
case ImGuiCol_NavWindowingHighlight: return "NavWindowingHighlight";
case ImGuiCol_NavWindowingDimBg: return "NavWindowingDimBg";
case ImGuiCol_ModalWindowDimBg: return "ModalWindowDimBg";
}
IM_ASSERT(0);
return "Unknown";
}
bool ImGui::IsWindowChildOf(ImGuiWindow* window, ImGuiWindow* potential_parent)
{
if (window->RootWindow == potential_parent)
return true;
while (window != NULL)
{
if (window == potential_parent)
return true;
window = window->ParentWindow;
}
return false;
}
bool ImGui::IsWindowHovered(ImGuiHoveredFlags flags)
{
IM_ASSERT((flags & ImGuiHoveredFlags_AllowWhenOverlapped) == 0); // Flags not supported by this function
ImGuiContext& g = *GImGui;
if (flags & ImGuiHoveredFlags_AnyWindow)
{
if (g.HoveredWindow == NULL)
return false;
}
else
{
switch (flags & (ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows))
{
case ImGuiHoveredFlags_RootWindow | ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || g.HoveredWindow->RootWindowDockStop != g.CurrentWindow->RootWindowDockStop)
return false;
break;
case ImGuiHoveredFlags_RootWindow:
if (g.HoveredWindow != g.CurrentWindow->RootWindowDockStop)
return false;
break;
case ImGuiHoveredFlags_ChildWindows:
if (g.HoveredWindow == NULL || !IsWindowChildOf(g.HoveredWindow, g.CurrentWindow))
return false;
break;
default:
if (g.HoveredWindow != g.CurrentWindow)
return false;
break;
}
}
if (!IsWindowContentHoverable(g.HoveredRootWindow, flags))
return false;
if (!(flags & ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
if (g.ActiveId != 0 && !g.ActiveIdAllowOverlap && g.ActiveId != g.HoveredWindow->MoveId)
return false;
return true;
}
bool ImGui::IsWindowFocused(ImGuiFocusedFlags flags)
{
ImGuiContext& g = *GImGui;
if (flags & ImGuiFocusedFlags_AnyWindow)
return g.NavWindow != NULL;
IM_ASSERT(g.CurrentWindow); // Not inside a Begin()/End()
switch (flags & (ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows))
{
case ImGuiFocusedFlags_RootWindow | ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && g.NavWindow->RootWindowDockStop == g.CurrentWindow->RootWindowDockStop;
case ImGuiFocusedFlags_RootWindow:
return g.NavWindow == g.CurrentWindow->RootWindowDockStop;
case ImGuiFocusedFlags_ChildWindows:
return g.NavWindow && IsWindowChildOf(g.NavWindow, g.CurrentWindow);
default:
return g.NavWindow == g.CurrentWindow;
}
}
ImGuiID ImGui::GetWindowDockID()
{
ImGuiContext& g = *GImGui;
return g.CurrentWindow->DockId;
}
bool ImGui::IsWindowDocked()
{
ImGuiContext& g = *GImGui;
return g.CurrentWindow->DockIsActive;
}
// Can we focus this window with CTRL+TAB (or PadMenu + PadFocusPrev/PadFocusNext)
// Note that NoNavFocus makes the window not reachable with CTRL+TAB but it can still be focused with mouse or programmaticaly.
// If you want a window to never be focused, you may use the e.g. NoInputs flag.
bool ImGui::IsWindowNavFocusable(ImGuiWindow* window)
{
return window->Active && window == window->RootWindowDockStop && !(window->Flags & ImGuiWindowFlags_NoNavFocus);
}
float ImGui::GetWindowWidth()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.x;
}
float ImGui::GetWindowHeight()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->Size.y;
}
ImVec2 ImGui::GetWindowPos()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
return window->Pos;
}
void ImGui::SetWindowScrollX(ImGuiWindow* window, float new_scroll_x)
{
window->DC.CursorMaxPos.x += window->Scroll.x; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.x = new_scroll_x;
window->DC.CursorMaxPos.x -= window->Scroll.x;
}
void ImGui::SetWindowScrollY(ImGuiWindow* window, float new_scroll_y)
{
window->DC.CursorMaxPos.y += window->Scroll.y; // SizeContents is generally computed based on CursorMaxPos which is affected by scroll position, so we need to apply our change to it.
window->Scroll.y = new_scroll_y;
window->DC.CursorMaxPos.y -= window->Scroll.y;
}
void ImGui::SetWindowPos(ImGuiWindow* window, const ImVec2& pos, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowPosAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowPosAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
window->SetWindowPosVal = ImVec2(FLT_MAX, FLT_MAX);
// Set
const ImVec2 old_pos = window->Pos;
window->Pos = ImFloor(pos);
window->DC.CursorPos += (window->Pos - old_pos); // As we happen to move the window while it is being appended to (which is a bad idea - will smear) let's at least offset the cursor
window->DC.CursorMaxPos += (window->Pos - old_pos); // And more importantly we need to adjust this so size calculation doesn't get affected.
}
void ImGui::SetWindowPos(const ImVec2& pos, ImGuiCond cond)
{
ImGuiWindow* window = GetCurrentWindowRead();
SetWindowPos(window, pos, cond);
}
void ImGui::SetWindowPos(const char* name, const ImVec2& pos, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowPos(window, pos, cond);
}
ImVec2 ImGui::GetWindowSize()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Size;
}
void ImGui::SetWindowSize(ImGuiWindow* window, const ImVec2& size, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowSizeAllowFlags & cond) == 0)
return;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
window->SetWindowSizeAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
if (size.x > 0.0f)
{
window->AutoFitFramesX = 0;
window->SizeFull.x = ImFloor(size.x);
}
else
{
window->AutoFitFramesX = 2;
window->AutoFitOnlyGrows = false;
}
if (size.y > 0.0f)
{
window->AutoFitFramesY = 0;
window->SizeFull.y = ImFloor(size.y);
}
else
{
window->AutoFitFramesY = 2;
window->AutoFitOnlyGrows = false;
}
}
void ImGui::SetWindowSize(const ImVec2& size, ImGuiCond cond)
{
SetWindowSize(GImGui->CurrentWindow, size, cond);
}
void ImGui::SetWindowSize(const char* name, const ImVec2& size, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowSize(window, size, cond);
}
void ImGui::SetWindowCollapsed(ImGuiWindow* window, bool collapsed, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowCollapsedAllowFlags & cond) == 0)
return;
window->SetWindowCollapsedAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
// Set
window->Collapsed = collapsed;
}
static void SetWindowHitTestHole(ImGuiWindow* window, const ImVec2& pos, const ImVec2& size)
{
IM_ASSERT(window->HitTestHoleSize.x == 0); // We don't support multiple holes/hit test filters
window->HitTestHoleSize = ImVec2ih((short)size.x, (short)size.y);
window->HitTestHoleOffset = ImVec2ih((short)(pos.x - window->Pos.x), (short)(pos.y - window->Pos.y));
}
void ImGui::SetWindowCollapsed(bool collapsed, ImGuiCond cond)
{
SetWindowCollapsed(GImGui->CurrentWindow, collapsed, cond);
}
bool ImGui::IsWindowCollapsed()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Collapsed;
}
bool ImGui::IsWindowAppearing()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->Appearing;
}
void ImGui::SetWindowCollapsed(const char* name, bool collapsed, ImGuiCond cond)
{
if (ImGuiWindow* window = FindWindowByName(name))
SetWindowCollapsed(window, collapsed, cond);
}
void ImGui::SetWindowFocus()
{
FocusWindow(GImGui->CurrentWindow);
}
void ImGui::SetWindowFocus(const char* name)
{
if (name)
{
if (ImGuiWindow* window = FindWindowByName(name))
FocusWindow(window);
}
else
{
FocusWindow(NULL);
}
}
void ImGui::SetNextWindowPos(const ImVec2& pos, ImGuiCond cond, const ImVec2& pivot)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.PosVal = pos;
g.NextWindowData.PosPivotVal = pivot;
g.NextWindowData.PosCond = cond ? cond : ImGuiCond_Always;
g.NextWindowData.PosUndock = true;
}
#ifndef IMGUI_DISABLE_OBSOLETE_FUNCTIONS
void ImGui::SetNextWindowPosCenter(ImGuiCond cond)
{
ImGuiViewport* viewport = ImGui::GetMainViewport();
SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, cond, ImVec2(0.5f, 0.5f));
SetNextWindowViewport(viewport->ID);
}
#endif
void ImGui::SetNextWindowSize(const ImVec2& size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.SizeVal = size;
g.NextWindowData.SizeCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowSizeConstraints(const ImVec2& size_min, const ImVec2& size_max, ImGuiSizeCallback custom_callback, void* custom_callback_user_data)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.SizeConstraintCond = ImGuiCond_Always;
g.NextWindowData.SizeConstraintRect = ImRect(size_min, size_max);
g.NextWindowData.SizeCallback = custom_callback;
g.NextWindowData.SizeCallbackUserData = custom_callback_user_data;
}
void ImGui::SetNextWindowContentSize(const ImVec2& size)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.ContentSizeVal = size; // In Begin() we will add the size of window decorations (title bar, menu etc.) to that to form a SizeContents value.
g.NextWindowData.ContentSizeCond = ImGuiCond_Always;
}
void ImGui::SetNextWindowCollapsed(bool collapsed, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(cond == 0 || ImIsPowerOfTwo(cond)); // Make sure the user doesn't attempt to combine multiple condition flags.
g.NextWindowData.CollapsedVal = collapsed;
g.NextWindowData.CollapsedCond = cond ? cond : ImGuiCond_Always;
}
void ImGui::SetNextWindowFocus()
{
ImGuiContext& g = *GImGui;
g.NextWindowData.FocusCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
void ImGui::SetNextWindowBgAlpha(float alpha)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.BgAlphaVal = alpha;
g.NextWindowData.BgAlphaCond = ImGuiCond_Always; // Using a Cond member for consistency (may transition all of them to single flag set for fast Clear() op)
}
void ImGui::SetNextWindowViewport(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.ViewportCond = ImGuiCond_Always;
g.NextWindowData.ViewportId = id;
}
void ImGui::SetNextWindowDockID(ImGuiID id, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.DockCond = cond ? cond : ImGuiCond_Always;
g.NextWindowData.DockId = id;
}
void ImGui::SetNextWindowClass(const ImGuiWindowClass* window_class)
{
ImGuiContext& g = *GImGui;
g.NextWindowData.WindowClass = *window_class;
}
// FIXME: This is in window space (not screen space!)
ImVec2 ImGui::GetContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
ImVec2 mx = window->ContentsRegionRect.Max - window->Pos;
if (window->DC.ColumnsSet)
mx.x = GetColumnOffset(window->DC.ColumnsSet->Current + 1) - window->WindowPadding.x;
return mx;
}
ImVec2 ImGui::GetContentRegionAvail()
{
ImGuiWindow* window = GetCurrentWindowRead();
return GetContentRegionMax() - (window->DC.CursorPos - window->Pos);
}
float ImGui::GetContentRegionAvailWidth()
{
return GetContentRegionAvail().x;
}
// In window space (not screen space!)
ImVec2 ImGui::GetWindowContentRegionMin()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Min - window->Pos;
}
ImVec2 ImGui::GetWindowContentRegionMax()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.Max - window->Pos;
}
float ImGui::GetWindowContentRegionWidth()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->ContentsRegionRect.GetWidth();
}
float ImGui::GetTextLineHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize;
}
float ImGui::GetTextLineHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.ItemSpacing.y;
}
float ImGui::GetFrameHeight()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f;
}
float ImGui::GetFrameHeightWithSpacing()
{
ImGuiContext& g = *GImGui;
return g.FontSize + g.Style.FramePadding.y * 2.0f + g.Style.ItemSpacing.y;
}
ImDrawList* ImGui::GetWindowDrawList()
{
ImGuiWindow* window = GetCurrentWindow();
return window->DrawList;
}
float ImGui::GetWindowDpiScale()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentViewport != NULL);
return g.CurrentViewport->DpiScale;
}
ImGuiViewport* ImGui::GetWindowViewport()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentViewport != NULL && g.CurrentViewport == g.CurrentWindow->Viewport);
return g.CurrentViewport;
}
ImFont* ImGui::GetFont()
{
return GImGui->Font;
}
float ImGui::GetFontSize()
{
return GImGui->FontSize;
}
ImVec2 ImGui::GetFontTexUvWhitePixel()
{
return GImGui->DrawListSharedData.TexUvWhitePixel;
}
void ImGui::SetWindowFontScale(float scale)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->FontWindowScale = scale;
g.FontSize = g.DrawListSharedData.FontSize = window->CalcFontSize();
}
// User generally sees positions in window coordinates. Internally we store CursorPos in absolute screen coordinates because it is more convenient.
// Conversion happens as we pass the value to user, but it makes our naming convention confusing because GetCursorPos() == (DC.CursorPos - window.Pos). May want to rename 'DC.CursorPos'.
ImVec2 ImGui::GetCursorPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos - window->Pos + window->Scroll;
}
float ImGui::GetCursorPosX()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.x - window->Pos.x + window->Scroll.x;
}
float ImGui::GetCursorPosY()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos.y - window->Pos.y + window->Scroll.y;
}
void ImGui::SetCursorPos(const ImVec2& local_pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = window->Pos - window->Scroll + local_pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
void ImGui::SetCursorPosX(float x)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + x;
window->DC.CursorMaxPos.x = ImMax(window->DC.CursorMaxPos.x, window->DC.CursorPos.x);
}
void ImGui::SetCursorPosY(float y)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos.y = window->Pos.y - window->Scroll.y + y;
window->DC.CursorMaxPos.y = ImMax(window->DC.CursorMaxPos.y, window->DC.CursorPos.y);
}
ImVec2 ImGui::GetCursorStartPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorStartPos - window->Pos;
}
ImVec2 ImGui::GetCursorScreenPos()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.CursorPos;
}
void ImGui::SetCursorScreenPos(const ImVec2& pos)
{
ImGuiWindow* window = GetCurrentWindow();
window->DC.CursorPos = pos;
window->DC.CursorMaxPos = ImMax(window->DC.CursorMaxPos, window->DC.CursorPos);
}
float ImGui::GetScrollX()
{
return GImGui->CurrentWindow->Scroll.x;
}
float ImGui::GetScrollY()
{
return GImGui->CurrentWindow->Scroll.y;
}
float ImGui::GetScrollMaxX()
{
return GetWindowScrollMaxX(GImGui->CurrentWindow);
}
float ImGui::GetScrollMaxY()
{
return GetWindowScrollMaxY(GImGui->CurrentWindow);
}
void ImGui::SetScrollX(float scroll_x)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.x = scroll_x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
void ImGui::SetScrollY(float scroll_y)
{
ImGuiWindow* window = GetCurrentWindow();
window->ScrollTarget.y = scroll_y + window->TitleBarHeight() + window->MenuBarHeight(); // title bar height canceled out when using ScrollTargetRelY
window->ScrollTargetCenterRatio.y = 0.0f;
}
void ImGui::SetScrollFromPosY(float local_y, float center_y_ratio)
{
// We store a target position so centering can occur on the next frame when we are guaranteed to have a known window size
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(center_y_ratio >= 0.0f && center_y_ratio <= 1.0f);
window->ScrollTarget.y = (float)(int)(local_y + window->Scroll.y);
window->ScrollTargetCenterRatio.y = center_y_ratio;
}
// center_y_ratio: 0.0f top of last item, 0.5f vertical center of last item, 1.0f bottom of last item.
void ImGui::SetScrollHereY(float center_y_ratio)
{
ImGuiWindow* window = GetCurrentWindow();
float target_y = window->DC.CursorPosPrevLine.y - window->Pos.y; // Top of last item, in window space
target_y += (window->DC.PrevLineSize.y * center_y_ratio) + (GImGui->Style.ItemSpacing.y * (center_y_ratio - 0.5f) * 2.0f); // Precisely aim above, in the middle or below the last line.
SetScrollFromPosY(target_y, center_y_ratio);
}
void ImGui::ActivateItem(ImGuiID id)
{
ImGuiContext& g = *GImGui;
g.NavNextActivateId = id;
}
void ImGui::SetKeyboardFocusHere(int offset)
{
IM_ASSERT(offset >= -1); // -1 is allowed but not below
ImGuiWindow* window = GetCurrentWindow();
window->FocusIdxAllRequestNext = window->FocusIdxAllCounter + 1 + offset;
window->FocusIdxTabRequestNext = INT_MAX;
}
void ImGui::SetItemDefaultFocus()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!window->Appearing)
return;
if (g.NavWindow == window->RootWindowForNav && (g.NavInitRequest || g.NavInitResultId != 0) && g.NavLayer == g.NavWindow->DC.NavLayerCurrent)
{
g.NavInitRequest = false;
g.NavInitResultId = g.NavWindow->DC.LastItemId;
g.NavInitResultRectRel = ImRect(g.NavWindow->DC.LastItemRect.Min - g.NavWindow->Pos, g.NavWindow->DC.LastItemRect.Max - g.NavWindow->Pos);
NavUpdateAnyRequestFlag();
if (!IsItemVisible())
SetScrollHereY();
}
}
void ImGui::SetStateStorage(ImGuiStorage* tree)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->DC.StateStorage = tree ? tree : &window->StateStorage;
}
ImGuiStorage* ImGui::GetStateStorage()
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->DC.StateStorage;
}
void ImGui::PushID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id));
}
void ImGui::PushID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(str_id_begin, str_id_end));
}
void ImGui::PushID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PushID(int int_id)
{
const void* ptr_id = (void*)(intptr_t)int_id;
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.push_back(window->GetIDNoKeepAlive(ptr_id));
}
void ImGui::PopID()
{
ImGuiWindow* window = GImGui->CurrentWindow;
window->IDStack.pop_back();
}
ImGuiID ImGui::GetID(const char* str_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id);
}
ImGuiID ImGui::GetID(const char* str_id_begin, const char* str_id_end)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(str_id_begin, str_id_end);
}
ImGuiID ImGui::GetID(const void* ptr_id)
{
ImGuiWindow* window = GImGui->CurrentWindow;
return window->GetID(ptr_id);
}
bool ImGui::IsRectVisible(const ImVec2& size)
{
ImGuiWindow* window = GImGui->CurrentWindow;;
return window->ClipRect.Overlaps(ImRect(window->DC.CursorPos, window->DC.CursorPos + size));
}
bool ImGui::IsRectVisible(const ImVec2& rect_min, const ImVec2& rect_max)
{
ImGuiWindow* window = GImGui->CurrentWindow;;
return window->ClipRect.Overlaps(ImRect(rect_min, rect_max));
}
// Lock horizontal starting position + capture group bounding box into one "item" (so you can use IsItemHovered() or layout primitives such as SameLine() on whole group, etc.)
void ImGui::BeginGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.GroupStack.resize(window->DC.GroupStack.Size + 1);
ImGuiGroupData& group_data = window->DC.GroupStack.back();
group_data.BackupCursorPos = window->DC.CursorPos;
group_data.BackupCursorMaxPos = window->DC.CursorMaxPos;
group_data.BackupIndent = window->DC.Indent;
group_data.BackupGroupOffset = window->DC.GroupOffset;
group_data.BackupCurrentLineSize = window->DC.CurrentLineSize;
group_data.BackupCurrentLineTextBaseOffset = window->DC.CurrentLineTextBaseOffset;
group_data.BackupLogLinePosY = window->DC.LogLinePosY;
group_data.BackupActiveIdIsAlive = g.ActiveIdIsAlive;
group_data.BackupActiveIdPreviousFrameIsAlive = g.ActiveIdPreviousFrameIsAlive;
group_data.AdvanceCursor = true;
window->DC.GroupOffset.x = window->DC.CursorPos.x - window->Pos.x - window->DC.ColumnsOffset.x;
window->DC.Indent = window->DC.GroupOffset;
window->DC.CursorMaxPos = window->DC.CursorPos;
window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
}
void ImGui::EndGroup()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(!window->DC.GroupStack.empty()); // Mismatched BeginGroup()/EndGroup() calls
ImGuiGroupData& group_data = window->DC.GroupStack.back();
ImRect group_bb(group_data.BackupCursorPos, window->DC.CursorMaxPos);
group_bb.Max = ImMax(group_bb.Min, group_bb.Max);
window->DC.CursorPos = group_data.BackupCursorPos;
window->DC.CursorMaxPos = ImMax(group_data.BackupCursorMaxPos, window->DC.CursorMaxPos);
window->DC.Indent = group_data.BackupIndent;
window->DC.GroupOffset = group_data.BackupGroupOffset;
window->DC.CurrentLineSize = group_data.BackupCurrentLineSize;
window->DC.CurrentLineTextBaseOffset = group_data.BackupCurrentLineTextBaseOffset;
window->DC.LogLinePosY = window->DC.CursorPos.y - 9999.0f; // To enforce Log carriage return
if (group_data.AdvanceCursor)
{
window->DC.CurrentLineTextBaseOffset = ImMax(window->DC.PrevLineTextBaseOffset, group_data.BackupCurrentLineTextBaseOffset); // FIXME: Incorrect, we should grab the base offset from the *first line* of the group but it is hard to obtain now.
ItemSize(group_bb.GetSize(), 0.0f);
ItemAdd(group_bb, 0);
}
// If the current ActiveId was declared within the boundary of our group, we copy it to LastItemId so IsItemActive(), IsItemDeactivated() etc. will be functional on the entire group.
// It would be be neater if we replaced window.DC.LastItemId by e.g. 'bool LastItemIsActive', but would put a little more burden on individual widgets.
// (and if you grep for LastItemId you'll notice it is only used in that context.
if ((group_data.BackupActiveIdIsAlive != g.ActiveId) && (g.ActiveIdIsAlive == g.ActiveId) && g.ActiveId) // && g.ActiveIdWindow->RootWindow == window->RootWindow)
window->DC.LastItemId = g.ActiveId;
else if (!group_data.BackupActiveIdPreviousFrameIsAlive && g.ActiveIdPreviousFrameIsAlive) // && g.ActiveIdPreviousFrameWindow->RootWindow == window->RootWindow)
window->DC.LastItemId = g.ActiveIdPreviousFrame;
window->DC.LastItemRect = group_bb;
window->DC.GroupStack.pop_back();
//window->DrawList->AddRect(group_bb.Min, group_bb.Max, IM_COL32(255,0,255,255)); // [Debug]
}
// Gets back to previous line and continue with horizontal layout
// pos_x == 0 : follow right after previous item
// pos_x != 0 : align to specified x position (relative to window/group left)
// spacing_w < 0 : use default spacing if pos_x == 0, no spacing if pos_x != 0
// spacing_w >= 0 : enforce spacing amount
void ImGui::SameLine(float pos_x, float spacing_w)
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems)
return;
ImGuiContext& g = *GImGui;
if (pos_x != 0.0f)
{
if (spacing_w < 0.0f) spacing_w = 0.0f;
window->DC.CursorPos.x = window->Pos.x - window->Scroll.x + pos_x + spacing_w + window->DC.GroupOffset.x + window->DC.ColumnsOffset.x;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
else
{
if (spacing_w < 0.0f) spacing_w = g.Style.ItemSpacing.x;
window->DC.CursorPos.x = window->DC.CursorPosPrevLine.x + spacing_w;
window->DC.CursorPos.y = window->DC.CursorPosPrevLine.y;
}
window->DC.CurrentLineSize = window->DC.PrevLineSize;
window->DC.CurrentLineTextBaseOffset = window->DC.PrevLineTextBaseOffset;
}
void ImGui::Indent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x += (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
void ImGui::Unindent(float indent_w)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
window->DC.Indent.x -= (indent_w != 0.0f) ? indent_w : g.Style.IndentSpacing;
window->DC.CursorPos.x = window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x;
}
//-----------------------------------------------------------------------------
// [SECTION] TOOLTIPS
//-----------------------------------------------------------------------------
void ImGui::BeginTooltip()
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
{
// The default tooltip position is a little offset to give space to see the context menu (it's also clamped within the current viewport/monitor)
// In the context of a dragging tooltip we try to reduce that offset and we enforce following the cursor.
// Whatever we do we want to call SetNextWindowPos() to enforce a tooltip position and disable clipping the tooltip without our display area, like regular tooltip do.
//ImVec2 tooltip_pos = g.IO.MousePos - g.ActiveIdClickOffset - g.Style.WindowPadding;
ImVec2 tooltip_pos = g.IO.MousePos + ImVec2(16 * g.Style.MouseCursorScale, 8 * g.Style.MouseCursorScale);
SetNextWindowPos(tooltip_pos);
SetNextWindowBgAlpha(g.Style.Colors[ImGuiCol_PopupBg].w * 0.60f);
//PushStyleVar(ImGuiStyleVar_Alpha, g.Style.Alpha * 0.60f); // This would be nice but e.g ColorButton with checkboard has issue with transparent colors :(
BeginTooltipEx(0, true);
}
else
{
BeginTooltipEx(0, false);
}
}
// Not exposed publicly as BeginTooltip() because bool parameters are evil. Let's see if other needs arise first.
void ImGui::BeginTooltipEx(ImGuiWindowFlags extra_flags, bool override_previous_tooltip)
{
ImGuiContext& g = *GImGui;
char window_name[16];
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", g.TooltipOverrideCount);
if (override_previous_tooltip)
if (ImGuiWindow* window = FindWindowByName(window_name))
if (window->Active)
{
// Hide previous tooltip from being displayed. We can't easily "reset" the content of a window so we create a new one.
window->Hidden = true;
window->HiddenFramesRegular = 1;
ImFormatString(window_name, IM_ARRAYSIZE(window_name), "##Tooltip_%02d", ++g.TooltipOverrideCount);
}
ImGuiWindowFlags flags = ImGuiWindowFlags_Tooltip|ImGuiWindowFlags_NoInputs|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoMove|ImGuiWindowFlags_NoResize|ImGuiWindowFlags_NoSavedSettings|ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoDocking;
Begin(window_name, NULL, flags | extra_flags);
}
void ImGui::EndTooltip()
{
IM_ASSERT(GetCurrentWindowRead()->Flags & ImGuiWindowFlags_Tooltip); // Mismatched BeginTooltip()/EndTooltip() calls
End();
}
void ImGui::SetTooltipV(const char* fmt, va_list args)
{
ImGuiContext& g = *GImGui;
if (g.DragDropWithinSourceOrTarget)
BeginTooltip();
else
BeginTooltipEx(0, true);
TextV(fmt, args);
EndTooltip();
}
void ImGui::SetTooltip(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
SetTooltipV(fmt, args);
va_end(args);
}
//-----------------------------------------------------------------------------
// [SECTION] POPUPS
//-----------------------------------------------------------------------------
bool ImGui::IsPopupOpen(ImGuiID id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == id;
}
bool ImGui::IsPopupOpen(const char* str_id)
{
ImGuiContext& g = *GImGui;
return g.OpenPopupStack.Size > g.BeginPopupStack.Size && g.OpenPopupStack[g.BeginPopupStack.Size].PopupId == g.CurrentWindow->GetID(str_id);
}
ImGuiWindow* ImGui::GetFrontMostPopupModal()
{
ImGuiContext& g = *GImGui;
for (int n = g.OpenPopupStack.Size-1; n >= 0; n--)
if (ImGuiWindow* popup = g.OpenPopupStack.Data[n].Window)
if (popup->Flags & ImGuiWindowFlags_Modal)
return popup;
return NULL;
}
void ImGui::OpenPopup(const char* str_id)
{
ImGuiContext& g = *GImGui;
OpenPopupEx(g.CurrentWindow->GetID(str_id));
}
// Mark popup as open (toggle toward open state).
// Popups are closed when user click outside, or activate a pressable item, or CloseCurrentPopup() is called within a BeginPopup()/EndPopup() block.
// Popup identifiers are relative to the current ID-stack (so OpenPopup and BeginPopup needs to be at the same level).
// One open popup per level of the popup hierarchy (NB: when assigning we reset the Window member of ImGuiPopupRef to NULL)
void ImGui::OpenPopupEx(ImGuiID id)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* parent_window = g.CurrentWindow;
int current_stack_size = g.BeginPopupStack.Size;
ImGuiPopupRef popup_ref; // Tagged as new ref as Window will be set back to NULL if we write this into OpenPopupStack.
popup_ref.PopupId = id;
popup_ref.Window = NULL;
popup_ref.ParentWindow = parent_window;
popup_ref.OpenFrameCount = g.FrameCount;
popup_ref.OpenParentId = parent_window->IDStack.back();
popup_ref.OpenPopupPos = NavCalcPreferredRefPos();
popup_ref.OpenMousePos = IsMousePosValid(&g.IO.MousePos) ? g.IO.MousePos : popup_ref.OpenPopupPos;
//IMGUI_DEBUG_LOG("OpenPopupEx(0x%08X)\n", g.FrameCount, id);
if (g.OpenPopupStack.Size < current_stack_size + 1)
{
g.OpenPopupStack.push_back(popup_ref);
}
else
{
// Gently handle the user mistakenly calling OpenPopup() every frame. It is a programming mistake! However, if we were to run the regular code path, the ui
// would become completely unusable because the popup will always be in hidden-while-calculating-size state _while_ claiming focus. Which would be a very confusing
// situation for the programmer. Instead, we silently allow the popup to proceed, it will keep reappearing and the programming error will be more obvious to understand.
if (g.OpenPopupStack[current_stack_size].PopupId == id && g.OpenPopupStack[current_stack_size].OpenFrameCount == g.FrameCount - 1)
{
g.OpenPopupStack[current_stack_size].OpenFrameCount = popup_ref.OpenFrameCount;
}
else
{
// Close child popups if any, then flag popup for open/reopen
g.OpenPopupStack.resize(current_stack_size + 1);
g.OpenPopupStack[current_stack_size] = popup_ref;
}
// When reopening a popup we first refocus its parent, otherwise if its parent is itself a popup it would get closed by ClosePopupsOverWindow().
// This is equivalent to what ClosePopupToLevel() does.
//if (g.OpenPopupStack[current_stack_size].PopupId == id)
// FocusWindow(parent_window);
}
}
bool ImGui::OpenPopupOnItemClick(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
{
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
OpenPopupEx(id);
return true;
}
return false;
}
void ImGui::ClosePopupsOverWindow(ImGuiWindow* ref_window)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.empty())
return;
// When popups are stacked, clicking on a lower level popups puts focus back to it and close popups above it.
// Don't close our own child popup windows.
int popup_count_to_keep = 0;
if (ref_window)
{
// Find the highest popup which is a descendant of the reference window (generally reference window = NavWindow)
for (; popup_count_to_keep < g.OpenPopupStack.Size; popup_count_to_keep++)
{
ImGuiPopupRef& popup = g.OpenPopupStack[popup_count_to_keep];
if (!popup.Window)
continue;
IM_ASSERT((popup.Window->Flags & ImGuiWindowFlags_Popup) != 0);
if (popup.Window->Flags & ImGuiWindowFlags_ChildWindow)
continue;
// Trim the stack if popups are not direct descendant of the reference window (which is often the NavWindow)
bool popup_or_descendent_has_focus = false;
for (int m = popup_count_to_keep; m < g.OpenPopupStack.Size && !popup_or_descendent_has_focus; m++)
if (g.OpenPopupStack[m].Window && g.OpenPopupStack[m].Window->RootWindow == ref_window->RootWindow)
popup_or_descendent_has_focus = true;
if (!popup_or_descendent_has_focus)
break;
}
}
if (popup_count_to_keep < g.OpenPopupStack.Size) // This test is not required but it allows to set a convenient breakpoint on the statement below
{
//IMGUI_DEBUG_LOG("ClosePopupsOverWindow(%s) -> ClosePopupToLevel(%d)\n", ref_window->Name, popup_count_to_keep);
ClosePopupToLevel(popup_count_to_keep, false);
}
}
void ImGui::ClosePopupToLevel(int remaining, bool apply_focus_to_window_under)
{
IM_ASSERT(remaining >= 0);
ImGuiContext& g = *GImGui;
ImGuiWindow* focus_window = (remaining > 0) ? g.OpenPopupStack[remaining-1].Window : g.OpenPopupStack[0].ParentWindow;
g.OpenPopupStack.resize(remaining);
// FIXME: This code is faulty and we may want to eventually to replace or remove the 'apply_focus_to_window_under=true' path completely.
// Instead of using g.OpenPopupStack[remaining-1].Window etc. we should find the highest root window that is behind the popups we are closing.
// The current code will set focus to the parent of the popup window which is incorrect.
// It rarely manifested until now because UpdateMouseMovingWindowNewFrame() would call FocusWindow() again on the clicked window,
// leading to a chain of focusing A (clicked window) then B (parent window of the popup) then A again.
// However if the clicked window has the _NoMove flag set we would be left with B focused.
// For now, we have disabled this path when called from ClosePopupsOverWindow() because the users of ClosePopupsOverWindow() don't need to alter focus anyway,
// but we should inspect and fix this properly.
if (apply_focus_to_window_under)
{
if (g.NavLayer == 0)
focus_window = NavRestoreLastChildNavWindow(focus_window);
FocusWindow(focus_window);
}
}
// Close the popup we have begin-ed into.
void ImGui::CloseCurrentPopup()
{
ImGuiContext& g = *GImGui;
int popup_idx = g.BeginPopupStack.Size - 1;
if (popup_idx < 0 || popup_idx >= g.OpenPopupStack.Size || g.BeginPopupStack[popup_idx].PopupId != g.OpenPopupStack[popup_idx].PopupId)
return;
// Closing a menu closes its top-most parent popup (unless a modal)
while (popup_idx > 0)
{
ImGuiWindow* popup_window = g.OpenPopupStack[popup_idx].Window;
ImGuiWindow* parent_popup_window = g.OpenPopupStack[popup_idx - 1].Window;
bool close_parent = false;
if (popup_window && (popup_window->Flags & ImGuiWindowFlags_ChildMenu))
if (parent_popup_window == NULL || !(parent_popup_window->Flags & ImGuiWindowFlags_Modal))
close_parent = true;
if (!close_parent)
break;
popup_idx--;
}
//IMGUI_DEBUG_LOG("CloseCurrentPopup %d -> %d\n", g.BeginPopupStack.Size - 1, popup_idx);
ClosePopupToLevel(popup_idx, true);
// A common pattern is to close a popup when selecting a menu item/selectable that will open another window.
// To improve this usage pattern, we avoid nav highlight for a single frame in the parent window.
// Similarly, we could avoid mouse hover highlight in this window but it is less visually problematic.
if (ImGuiWindow* window = g.NavWindow)
window->DC.NavHideHighlightOneFrame = true;
}
bool ImGui::BeginPopupEx(ImGuiID id, ImGuiWindowFlags extra_flags)
{
ImGuiContext& g = *GImGui;
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
char name[20];
if (extra_flags & ImGuiWindowFlags_ChildMenu)
ImFormatString(name, IM_ARRAYSIZE(name), "##Menu_%02d", g.BeginPopupStack.Size); // Recycle windows based on depth
else
ImFormatString(name, IM_ARRAYSIZE(name), "##Popup_%08x", id); // Not recycling, so we can close/open during the same frame
bool is_open = Begin(name, NULL, extra_flags | ImGuiWindowFlags_Popup);
if (!is_open) // NB: Begin can return false when the popup is completely clipped (e.g. zero size display)
EndPopup();
return is_open;
}
bool ImGui::BeginPopup(const char* str_id, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
if (g.OpenPopupStack.Size <= g.BeginPopupStack.Size) // Early out for performance
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
flags |= ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking;
return BeginPopupEx(g.CurrentWindow->GetID(str_id), flags);
}
// If 'p_open' is specified for a modal popup window, the popup will have a regular close button which will close the popup.
// Note that popup visibility status is owned by imgui (and manipulated with e.g. OpenPopup) so the actual value of *p_open is meaningless here.
bool ImGui::BeginPopupModal(const char* name, bool* p_open, ImGuiWindowFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
const ImGuiID id = window->GetID(name);
if (!IsPopupOpen(id))
{
g.NextWindowData.Clear(); // We behave like Begin() and need to consume those values
return false;
}
// Center modal windows by default
// FIXME: Should test for (PosCond & window->SetWindowPosAllowFlags) with the upcoming window.
if (g.NextWindowData.PosCond == 0)
SetNextWindowPos(window->Viewport->GetCenter(), ImGuiCond_Appearing, ImVec2(0.5f, 0.5f));
flags |= ImGuiWindowFlags_Popup | ImGuiWindowFlags_Modal | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoDocking;
const bool is_open = Begin(name, p_open, flags);
if (!is_open || (p_open && !*p_open)) // NB: is_open can be 'false' when the popup is completely clipped (e.g. zero size display)
{
EndPopup();
if (is_open)
ClosePopupToLevel(g.BeginPopupStack.Size, true);
return false;
}
return is_open;
}
void ImGui::EndPopup()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindow->Flags & ImGuiWindowFlags_Popup); // Mismatched BeginPopup()/EndPopup() calls
IM_ASSERT(g.BeginPopupStack.Size > 0);
// Make all menus and popups wrap around for now, may need to expose that policy.
NavMoveRequestTryWrapping(g.CurrentWindow, ImGuiNavMoveFlags_LoopY);
End();
}
// This is a helper to handle the simplest case of associating one named popup to one given widget.
// You may want to handle this on user side if you have specific needs (e.g. tweaking IsItemHovered() parameters).
// You can pass a NULL str_id to use the identifier of the last item.
bool ImGui::BeginPopupContextItem(const char* str_id, int mouse_button)
{
ImGuiWindow* window = GImGui->CurrentWindow;
ImGuiID id = str_id ? window->GetID(str_id) : window->DC.LastItemId; // If user hasn't passed an ID, we can use the LastItemID. Using LastItemID as a Popup ID won't conflict!
IM_ASSERT(id != 0); // You cannot pass a NULL str_id if the last item has no identifier (e.g. a Text() item)
if (IsMouseReleased(mouse_button) && IsItemHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextWindow(const char* str_id, int mouse_button, bool also_over_items)
{
if (!str_id)
str_id = "window_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByPopup))
if (also_over_items || !IsAnyItemHovered())
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
bool ImGui::BeginPopupContextVoid(const char* str_id, int mouse_button)
{
if (!str_id)
str_id = "void_context";
ImGuiID id = GImGui->CurrentWindow->GetID(str_id);
if (IsMouseReleased(mouse_button) && !IsWindowHovered(ImGuiHoveredFlags_AnyWindow))
OpenPopupEx(id);
return BeginPopupEx(id, ImGuiWindowFlags_AlwaysAutoResize|ImGuiWindowFlags_NoTitleBar|ImGuiWindowFlags_NoSavedSettings);
}
// r_avoid = the rectangle to avoid (e.g. for tooltip it is a rectangle around the mouse cursor which we want to avoid. for popups it's a small point around the cursor.)
// r_outer = the visible area rectangle, minus safe area padding. If our popup size won't fit because of safe area padding we ignore it.
// (r_outer is usually equivalent to the viewport rectangle minus padding, but when multi-viewports are enabled and monitor
// information are available, it may represent the entire platform monitor from the frame of reference of the current viewport.
// this allows us to have tooltips/popups displayed out of the parent viewport.)
ImVec2 ImGui::FindBestWindowPosForPopupEx(const ImVec2& ref_pos, const ImVec2& size, ImGuiDir* last_dir, const ImRect& r_outer, const ImRect& r_avoid, ImGuiPopupPositionPolicy policy)
{
ImVec2 base_pos_clamped = ImClamp(ref_pos, r_outer.Min, r_outer.Max - size);
//GImGui->OverlayDrawList.AddRect(r_avoid.Min, r_avoid.Max, IM_COL32(255,0,0,255));
//GImGui->OverlayDrawList.AddRect(r_outer.Min, r_outer.Max, IM_COL32(0,255,0,255));
// Combo Box policy (we want a connecting edge)
if (policy == ImGuiPopupPositionPolicy_ComboBox)
{
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Down, ImGuiDir_Right, ImGuiDir_Left, ImGuiDir_Up };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
ImVec2 pos;
if (dir == ImGuiDir_Down) pos = ImVec2(r_avoid.Min.x, r_avoid.Max.y); // Below, Toward Right (default)
if (dir == ImGuiDir_Right) pos = ImVec2(r_avoid.Min.x, r_avoid.Min.y - size.y); // Above, Toward Right
if (dir == ImGuiDir_Left) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Max.y); // Below, Toward Left
if (dir == ImGuiDir_Up) pos = ImVec2(r_avoid.Max.x - size.x, r_avoid.Min.y - size.y); // Above, Toward Left
if (!r_outer.Contains(ImRect(pos, pos + size)))
continue;
*last_dir = dir;
return pos;
}
}
// Default popup policy
const ImGuiDir dir_prefered_order[ImGuiDir_COUNT] = { ImGuiDir_Right, ImGuiDir_Down, ImGuiDir_Up, ImGuiDir_Left };
for (int n = (*last_dir != ImGuiDir_None) ? -1 : 0; n < ImGuiDir_COUNT; n++)
{
const ImGuiDir dir = (n == -1) ? *last_dir : dir_prefered_order[n];
if (n != -1 && dir == *last_dir) // Already tried this direction?
continue;
float avail_w = (dir == ImGuiDir_Left ? r_avoid.Min.x : r_outer.Max.x) - (dir == ImGuiDir_Right ? r_avoid.Max.x : r_outer.Min.x);
float avail_h = (dir == ImGuiDir_Up ? r_avoid.Min.y : r_outer.Max.y) - (dir == ImGuiDir_Down ? r_avoid.Max.y : r_outer.Min.y);
if (avail_w < size.x || avail_h < size.y)
continue;
ImVec2 pos;
pos.x = (dir == ImGuiDir_Left) ? r_avoid.Min.x - size.x : (dir == ImGuiDir_Right) ? r_avoid.Max.x : base_pos_clamped.x;
pos.y = (dir == ImGuiDir_Up) ? r_avoid.Min.y - size.y : (dir == ImGuiDir_Down) ? r_avoid.Max.y : base_pos_clamped.y;
*last_dir = dir;
return pos;
}
// Fallback, try to keep within display
*last_dir = ImGuiDir_None;
ImVec2 pos = ref_pos;
pos.x = ImMax(ImMin(pos.x + size.x, r_outer.Max.x) - size.x, r_outer.Min.x);
pos.y = ImMax(ImMin(pos.y + size.y, r_outer.Max.y) - size.y, r_outer.Min.y);
return pos;
}
ImRect ImGui::GetWindowAllowedExtentRect(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImRect r_screen;
if (window->ViewportAllowPlatformMonitorExtend >= 0)
{
// Extent with be in the frame of reference of the given viewport (so Min is likely to be negative here)
const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[window->ViewportAllowPlatformMonitorExtend];
r_screen.Min = monitor.WorkPos;
r_screen.Max = monitor.WorkPos + monitor.WorkSize;
}
else
{
r_screen.Min = window->Viewport->Pos;
r_screen.Max = window->Viewport->Pos + window->Viewport->Size;
}
ImVec2 padding = g.Style.DisplaySafeAreaPadding;
r_screen.Expand(ImVec2((r_screen.GetWidth() > padding.x * 2) ? -padding.x : 0.0f, (r_screen.GetHeight() > padding.y * 2) ? -padding.y : 0.0f));
return r_screen;
}
ImVec2 ImGui::FindBestWindowPosForPopup(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (window->Flags & ImGuiWindowFlags_ChildMenu)
{
// Child menus typically request _any_ position within the parent menu item, and then we move the new menu outside the parent bounds.
// This is how we end up with child menus appearing (most-commonly) on the right of the parent menu.
ImGuiWindow* parent_window = window->ParentWindow;
float horizontal_overlap = g.Style.ItemInnerSpacing.x; // We want some overlap to convey the relative depth of each menu (currently the amount of overlap is hard-coded to style.ItemSpacing.x).
ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid;
if (parent_window->DC.MenuBarAppending)
r_avoid = ImRect(-FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight(), FLT_MAX, parent_window->Pos.y + parent_window->TitleBarHeight() + parent_window->MenuBarHeight());
else
r_avoid = ImRect(parent_window->Pos.x + horizontal_overlap, -FLT_MAX, parent_window->Pos.x + parent_window->Size.x - horizontal_overlap - parent_window->ScrollbarSizes.x, FLT_MAX);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Popup)
{
ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid = ImRect(window->Pos.x - 1, window->Pos.y - 1, window->Pos.x + 1, window->Pos.y + 1);
return FindBestWindowPosForPopupEx(window->Pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
}
if (window->Flags & ImGuiWindowFlags_Tooltip)
{
// Position tooltip (always follows mouse)
float sc = g.Style.MouseCursorScale;
ImVec2 ref_pos = NavCalcPreferredRefPos();
ImRect r_outer = GetWindowAllowedExtentRect(window);
ImRect r_avoid;
if (!g.NavDisableHighlight && g.NavDisableMouseHover && !(g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos))
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 16, ref_pos.y + 8);
else
r_avoid = ImRect(ref_pos.x - 16, ref_pos.y - 8, ref_pos.x + 24 * sc, ref_pos.y + 24 * sc); // FIXME: Hard-coded based on mouse cursor shape expectation. Exact dimension not very important.
ImVec2 pos = FindBestWindowPosForPopupEx(ref_pos, window->Size, &window->AutoPosLastDirection, r_outer, r_avoid);
if (window->AutoPosLastDirection == ImGuiDir_None)
pos = ref_pos + ImVec2(2, 2); // If there's not enough room, for tooltip we prefer avoiding the cursor at all cost even if it means that part of the tooltip won't be visible.
return pos;
}
IM_ASSERT(0);
return window->Pos;
}
//-----------------------------------------------------------------------------
// [SECTION] VIEWPORTS, PLATFORM WINDOWS
//-----------------------------------------------------------------------------
ImGuiViewport* ImGui::GetMainViewport()
{
ImGuiContext& g = *GImGui;
return g.Viewports[0];
}
ImGuiViewport* ImGui::FindViewportByID(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (int n = 0; n < g.Viewports.Size; n++)
if (g.Viewports[n]->ID == id)
return g.Viewports[n];
return NULL;
}
ImGuiViewport* ImGui::FindViewportByPlatformHandle(void* platform_handle)
{
ImGuiContext& g = *GImGui;
for (int i = 0; i != g.Viewports.Size; i++)
if (g.Viewports[i]->PlatformHandle == platform_handle)
return g.Viewports[i];
return NULL;
}
void ImGui::SetCurrentViewport(ImGuiWindow* current_window, ImGuiViewportP* viewport)
{
ImGuiContext& g = *GImGui;
(void)current_window;
if (viewport)
viewport->LastFrameActive = g.FrameCount;
if (g.CurrentViewport == viewport)
return;
g.CurrentViewport = viewport;
//IMGUI_DEBUG_LOG("SetCurrentViewport changed '%s' 0x%08X\n", current_window ? current_window->Name : NULL, viewport ? viewport->ID : 0);
// Notify platform layer of viewport changes
// FIXME-DPI: This is only currently used for experimenting with handling of multiple DPI
if (g.CurrentViewport && g.PlatformIO.Platform_OnChangedViewport)
g.PlatformIO.Platform_OnChangedViewport(g.CurrentViewport);
}
static void SetWindowViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
{
window->Viewport = viewport;
window->ViewportId = viewport->ID;
window->ViewportOwned = (viewport->Window == window);
}
static bool ImGui::GetWindowAlwaysWantOwnViewport(ImGuiWindow* window)
{
// Tooltips and menus are not automatically forced into their own viewport when the NoMerge flag is set, however the multiplication of viewports makes them more likely to protude and create their own.
ImGuiContext& g = *GImGui;
if (g.IO.ConfigViewportsNoAutoMerge && (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
if (!window->DockIsActive)
if ((window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_ChildMenu | ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup)) == 0)
return true;
return false;
}
static bool ImGui::UpdateTryMergeWindowIntoHostViewport(ImGuiWindow* window, ImGuiViewportP* viewport)
{
ImGuiContext& g = *GImGui;
if (!(viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) || window->Viewport == viewport || viewport->PlatformWindowMinimized)
return false;
if (!viewport->GetRect().Contains(window->Rect()))
return false;
if (GetWindowAlwaysWantOwnViewport(window))
return false;
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window_behind = g.Windows[n];
if (window_behind == window)
break;
if (window_behind->WasActive && window_behind->ViewportOwned && !(window_behind->Flags & ImGuiWindowFlags_ChildWindow))
if (window_behind->Viewport->GetRect().Overlaps(window->Rect()))
return false;
}
// Move to the existing viewport, Move child/hosted windows as well (FIXME-OPT: iterate child)
ImGuiViewportP* old_viewport = window->Viewport;
if (window->ViewportOwned)
for (int n = 0; n < g.Windows.Size; n++)
if (g.Windows[n]->Viewport == old_viewport)
SetWindowViewport(g.Windows[n], viewport);
SetWindowViewport(window, viewport);
BringWindowToDisplayFront(window);
return true;
}
// Scale all windows (position, size). Use when e.g. changing DPI. (This is a lossy operation!)
void ImGui::ScaleWindowsInViewport(ImGuiViewportP* viewport, float scale)
{
ImGuiContext& g = *GImGui;
if (viewport->Window)
{
ScaleWindow(viewport->Window, scale);
}
else
{
for (int i = 0; i != g.Windows.Size; i++)
if (g.Windows[i]->Viewport == viewport)
ScaleWindow(g.Windows[i], scale);
}
}
// If the back-end doesn't set MouseLastHoveredViewport or doesn't honor ImGuiViewportFlags_NoInputs, we do a search ourselves.
// A) It won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
// B) It requires Platform_GetWindowFocus to be implemented by back-end.
static ImGuiViewportP* FindViewportHoveredFromPlatformWindowStack(const ImVec2 mouse_platform_pos)
{
ImGuiContext& g = *GImGui;
ImGuiViewportP* best_candidate = NULL;
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
if (!(viewport->Flags & ImGuiViewportFlags_NoInputs) && !viewport->PlatformWindowMinimized && viewport->GetRect().Contains(mouse_platform_pos))
if (best_candidate == NULL || best_candidate->LastFrontMostStampCount < viewport->LastFrontMostStampCount)
best_candidate = viewport;
}
return best_candidate;
}
static void ImGui::UpdateViewportsNewFrame()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.PlatformIO.Viewports.Size <= g.Viewports.Size);
// Update Minimized status (we need it first in order to decide if we'll apply Pos/Size of the main viewport)
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated);
if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
if (g.PlatformIO.Platform_GetWindowMinimized && platform_funcs_available)
viewport->PlatformWindowMinimized = g.PlatformIO.Platform_GetWindowMinimized(viewport);
}
// Create/update main viewport with current platform position and size
ImGuiViewportP* main_viewport = g.Viewports[0];
IM_ASSERT(main_viewport->ID == IMGUI_VIEWPORT_DEFAULT_ID);
IM_ASSERT(main_viewport->Window == NULL);
ImVec2 main_viewport_platform_pos = ImVec2(0.0f, 0.0f);
ImVec2 main_viewport_platform_size = g.IO.DisplaySize;
if (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable)
main_viewport_platform_pos = main_viewport->PlatformWindowMinimized ? main_viewport->Pos : g.PlatformIO.Platform_GetWindowPos(main_viewport);
AddUpdateViewport(NULL, IMGUI_VIEWPORT_DEFAULT_ID, main_viewport_platform_pos, main_viewport_platform_size, ImGuiViewportFlags_CanHostOtherWindows);
g.CurrentViewport = NULL;
g.MouseViewport = NULL;
for (int n = 0; n < g.Viewports.Size; n++)
{
// Erase unused viewports
ImGuiViewportP* viewport = g.Viewports[n];
viewport->Idx = n;
if (n > 0 && viewport->LastFrameActive < g.FrameCount - 2)
{
// Clear references to this viewport in windows (window->ViewportId becomes the master data)
for (int window_n = 0; window_n < g.Windows.Size; window_n++)
if (g.Windows[window_n]->Viewport == viewport)
{
g.Windows[window_n]->Viewport = NULL;
g.Windows[window_n]->ViewportOwned = false;
}
if (viewport == g.MouseLastHoveredViewport)
g.MouseLastHoveredViewport = NULL;
g.Viewports.erase(g.Viewports.Data + n);
// Destroy
//IMGUI_DEBUG_LOG("Delete Viewport %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
DestroyPlatformWindow(viewport); // In most circumstances the platform window will already be destroyed here.
IM_ASSERT(g.PlatformIO.Viewports.contains(viewport) == false);
IM_DELETE(viewport);
n--;
continue;
}
const bool platform_funcs_available = (n == 0 || viewport->PlatformWindowCreated);
if ((g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
{
// Update Position and Size (from Platform Window to ImGui) if requested.
// We do it early in the frame instead of waiting for UpdatePlatformWindows() to avoid a frame of lag when moving/resizing using OS facilities.
if (!viewport->PlatformWindowMinimized && platform_funcs_available)
{
if (viewport->PlatformRequestMove)
viewport->Pos = viewport->LastPlatformPos = g.PlatformIO.Platform_GetWindowPos(viewport);
if (viewport->PlatformRequestResize)
viewport->Size = viewport->LastPlatformSize = g.PlatformIO.Platform_GetWindowSize(viewport);
}
// Update monitor (we'll use this info to clamp windows and save windows lost in a removed monitor)
viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect());
}
// Reset alpha every frame. Users of transparency (docking) needs to request a lower alpha back.
viewport->Alpha = 1.0f;
// Translate imgui windows when a Host Viewport has been moved
// (This additionally keeps windows at the same place when ImGuiConfigFlags_ViewportsEnable is toggled!)
ImVec2 viewport_delta = viewport->Pos - viewport->LastPos;
if ((viewport->Flags & ImGuiViewportFlags_CanHostOtherWindows) && (viewport_delta.x != 0.0f || viewport_delta.y != 0.0f))
for (int window_n = 0; window_n < g.Windows.Size; window_n++)
if (g.Windows[window_n]->Viewport == viewport || (g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable) == 0)
TranslateWindow(g.Windows[window_n], viewport_delta);
// Update DPI scale
float new_dpi_scale;
if (g.PlatformIO.Platform_GetWindowDpiScale && platform_funcs_available)
new_dpi_scale = g.PlatformIO.Platform_GetWindowDpiScale(viewport);
else if (viewport->PlatformMonitor != -1)
new_dpi_scale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
else
new_dpi_scale = (viewport->DpiScale != 0.0f) ? viewport->DpiScale : 1.0f;
if (viewport->DpiScale != 0.0f && new_dpi_scale != viewport->DpiScale)
{
float scale_factor = new_dpi_scale / viewport->DpiScale;
if (g.IO.ConfigFlags & ImGuiConfigFlags_DpiEnableScaleViewports)
ScaleWindowsInViewport(viewport, scale_factor);
//if (viewport == GetMainViewport())
// g.PlatformInterface.SetWindowSize(viewport, viewport->Size * scale_factor);
// Scale our window moving pivot so that the window will rescale roughly around the mouse position.
// FIXME-VIEWPORT: This currently creates a resizing feedback loop when a window is straddling a DPI transition border.
// (Minor: since our sizes do not perfectly linearly scale, deferring the click offset scale until we know the actual window scale ratio may get us slightly more precise mouse positioning.)
//if (g.MovingWindow != NULL && g.MovingWindow->Viewport == viewport)
// g.ActiveIdClickOffset = ImFloor(g.ActiveIdClickOffset * scale_factor);
}
viewport->DpiScale = new_dpi_scale;
}
if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
{
g.MouseViewport = main_viewport;
return;
}
// Mouse handling: decide on the actual mouse viewport for this frame between the active/focused viewport and the hovered viewport.
// Note that 'viewport_hovered' should skip over any viewport that has the ImGuiViewportFlags_NoInputs flags set.
ImGuiViewportP* viewport_hovered = NULL;
if (g.IO.BackendFlags & ImGuiBackendFlags_HasMouseHoveredViewport)
{
viewport_hovered = g.IO.MouseHoveredViewport ? (ImGuiViewportP*)FindViewportByID(g.IO.MouseHoveredViewport) : NULL;
if (viewport_hovered && (viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
{
// Back-end failed at honoring its contract if it returned a viewport with the _NoInputs flag.
IM_ASSERT(0);
viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos);
}
}
else
{
// If the back-end doesn't know how to honor ImGuiViewportFlags_NoInputs, we do a search ourselves. Note that this search:
// A) won't take account of the possibility that non-imgui windows may be in-between our dragged window and our target window.
// B) uses LastFrameAsRefViewport as a flawed replacement for the last time a window was focused (we could/should fix that by introducing Focus functions in PlatformIO)
viewport_hovered = FindViewportHoveredFromPlatformWindowStack(g.IO.MousePos);
}
if (viewport_hovered != NULL)
g.MouseLastHoveredViewport = viewport_hovered;
else if (g.MouseLastHoveredViewport == NULL)
g.MouseLastHoveredViewport = g.Viewports[0];
// Update mouse reference viewport
// (when moving a window we aim at its viewport, but this will be overwritten below if we go in drag and drop mode)
if (g.MovingWindow)
g.MouseViewport = g.MovingWindow->Viewport;
else
g.MouseViewport = g.MouseLastHoveredViewport;
// When dragging something, always refer to the last hovered viewport.
// - when releasing a moving window we will revert to aiming behind (at viewport_hovered)
// - when we are between viewports, our dragged preview will tend to show in the last viewport _even_ if we don't have tooltips in their viewports (when lacking monitor info)
// - consider the case of holding on a menu item to browse child menus: even thou a mouse button is held, there's no active id because menu items only react on mouse release.
const bool is_mouse_dragging_with_an_expected_destination = g.DragDropActive;
if (is_mouse_dragging_with_an_expected_destination && viewport_hovered == NULL)
viewport_hovered = g.MouseLastHoveredViewport;
if (is_mouse_dragging_with_an_expected_destination || g.ActiveId == 0 || !IsAnyMouseDown())
if (viewport_hovered != NULL && viewport_hovered != g.MouseViewport && !(viewport_hovered->Flags & ImGuiViewportFlags_NoInputs))
g.MouseViewport = viewport_hovered;
IM_ASSERT(g.MouseViewport != NULL);
}
// Update user-facing viewport list (g.Viewports -> g.PlatformIO.Viewports after filtering out some)
static void ImGui::UpdateViewportsEndFrame()
{
ImGuiContext& g = *GImGui;
g.PlatformIO.MainViewport = g.Viewports[0];
g.PlatformIO.Viewports.resize(0);
for (int i = 0; i < g.Viewports.Size; i++)
{
ImGuiViewportP* viewport = g.Viewports[i];
viewport->LastPos = viewport->Pos;
if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0.0f || viewport->Size.y <= 0.0f)
if (i > 0) // Always include main viewport in the list
continue;
if (viewport->Window && !IsWindowActiveAndVisible(viewport->Window))
continue;
if (i > 0)
IM_ASSERT(viewport->Window != NULL);
g.PlatformIO.Viewports.push_back(viewport);
}
g.Viewports[0]->ClearRequestFlags(); // Clear main viewport flags because UpdatePlatformWindows() won't do it and may not even be called
}
// FIXME: We should ideally refactor the system to call this every frame (we currently don't)
ImGuiViewportP* ImGui::AddUpdateViewport(ImGuiWindow* window, ImGuiID id, const ImVec2& pos, const ImVec2& size, ImGuiViewportFlags flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(id != 0);
if (window != NULL)
{
if (g.MovingWindow && g.MovingWindow->RootWindow == window)
flags |= ImGuiViewportFlags_NoInputs | ImGuiViewportFlags_NoFocusOnAppearing;
if ((window->Flags & ImGuiWindowFlags_NoMouseInputs) && (window->Flags & ImGuiWindowFlags_NoNavInputs))
flags |= ImGuiViewportFlags_NoInputs;
if (window->Flags & ImGuiWindowFlags_NoFocusOnAppearing)
flags |= ImGuiViewportFlags_NoFocusOnAppearing;
}
ImGuiViewportP* viewport = (ImGuiViewportP*)FindViewportByID(id);
if (viewport)
{
if (!viewport->PlatformRequestMove)
viewport->Pos = pos;
if (!viewport->PlatformRequestResize)
viewport->Size = size;
}
else
{
// New viewport
viewport = IM_NEW(ImGuiViewportP)();
viewport->ID = id;
viewport->Idx = g.Viewports.Size;
viewport->Pos = viewport->LastPos = pos;
viewport->Size = size;
viewport->PlatformMonitor = (short)FindPlatformMonitorForRect(viewport->GetRect());
g.Viewports.push_back(viewport);
//IMGUI_DEBUG_LOG("Add Viewport %08X (%s)\n", id, window->Name);
// We normally setup for all viewports in NewFrame() but here need to handle the mid-frame creation of a new viewport.
// We need to extend the fullscreen clip rect so the OverlayDrawList clip is correct for that the first frame
g.DrawListSharedData.ClipRectFullscreen.z = ImMax(g.DrawListSharedData.ClipRectFullscreen.z, viewport->Pos.x + viewport->Size.x);
g.DrawListSharedData.ClipRectFullscreen.w = ImMax(g.DrawListSharedData.ClipRectFullscreen.w, viewport->Pos.y + viewport->Size.y);
// Store initial DpiScale before the OS platform window creation, based on expected monitor data.
// This is so we can select an appropriate font size on the first frame of our window lifetime
if (viewport->PlatformMonitor != -1)
viewport->DpiScale = g.PlatformIO.Monitors[viewport->PlatformMonitor].DpiScale;
}
viewport->Window = window;
viewport->Flags = flags;
viewport->LastFrameActive = g.FrameCount;
IM_ASSERT(window == NULL || viewport->ID == window->ID);
if (window != NULL)
window->ViewportOwned = true;
return viewport;
}
// FIXME-VIEWPORT: This is all super messy and ought to be clarified or rewritten.
static void ImGui::UpdateSelectWindowViewport(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
ImGuiWindowFlags flags = window->Flags;
window->ViewportAllowPlatformMonitorExtend = -1;
// Restore main viewport if multi-viewport is not supported by the back-end
ImGuiViewportP* main_viewport = g.Viewports[0];
if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
{
SetWindowViewport(window, main_viewport);
return;
}
window->ViewportOwned = false;
// Appearing popups reset their viewport so they can inherit again
if ((flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_Tooltip)) && window->Appearing)
{
window->Viewport = NULL;
window->ViewportId = 0;
}
if (!g.NextWindowData.ViewportCond)
{
// By default inherit from parent window
if (window->Viewport == NULL && window->ParentWindow)
window->Viewport = window->ParentWindow->Viewport;
// Attempt to restore saved viewport id (= window that hasn't been activated yet), try to restore the viewport based on saved 'window->ViewportPos' restored from .ini file
if (window->Viewport == NULL && window->ViewportId != 0)
{
window->Viewport = (ImGuiViewportP*)FindViewportByID(window->ViewportId);
if (window->Viewport == NULL && window->ViewportPos.x != FLT_MAX && window->ViewportPos.y != FLT_MAX)
window->Viewport = AddUpdateViewport(window, window->ID, window->ViewportPos, window->Size, ImGuiViewportFlags_None);
}
}
if (g.NextWindowData.ViewportCond)
{
// Code explicitly request a viewport
window->Viewport = (ImGuiViewportP*)FindViewportByID(g.NextWindowData.ViewportId);
window->ViewportId = g.NextWindowData.ViewportId; // Store ID even if Viewport isn't resolved yet.
}
else if ((flags & ImGuiWindowFlags_ChildWindow) || (flags & ImGuiWindowFlags_ChildMenu))
{
// Always inherit viewport from parent window
window->Viewport = window->ParentWindow->Viewport;
}
else if (flags & ImGuiWindowFlags_Tooltip)
{
window->Viewport = g.MouseViewport;
}
else if (GetWindowAlwaysWantOwnViewport(window))
{
window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
}
else if (g.MovingWindow && g.MovingWindow->RootWindow == window && IsMousePosValid())
{
if (window->Viewport != NULL && window->Viewport->Window == window)
window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_None);
}
else
{
// Merge into host viewport?
// We cannot test window->ViewportOwned as it set lower in the function.
bool try_to_merge_into_host_viewport = (window->Viewport && window == window->Viewport->Window && g.ActiveId == 0);
if (try_to_merge_into_host_viewport)
UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0]);
}
// Fallback to default viewport
if (window->Viewport == NULL)
window->Viewport = main_viewport;
// Mark window as allowed to protrude outside of its viewport and into the current monitor
if (flags & (ImGuiWindowFlags_Tooltip | ImGuiWindowFlags_Popup))
{
// We need to take account of the possibility that mouse may become invalid.
// Popups/Tooltip always set ViewportAllowPlatformMonitorExtend so GetWindowAllowedExtentRect() will return full monitor bounds.
ImVec2 mouse_ref = (flags & ImGuiWindowFlags_Tooltip) ? g.IO.MousePos : g.BeginPopupStack.back().OpenMousePos;
bool use_mouse_ref = (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow);
bool mouse_valid = IsMousePosValid(&mouse_ref);
if ((window->Appearing || (flags & ImGuiWindowFlags_Tooltip)) && (!use_mouse_ref || mouse_valid))
window->ViewportAllowPlatformMonitorExtend = FindPlatformMonitorForPos((use_mouse_ref && mouse_valid) ? mouse_ref : NavCalcPreferredRefPos());
else
window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
}
else if (window->Viewport && window != window->Viewport->Window && window->Viewport->Window && !(flags & ImGuiWindowFlags_ChildWindow))
{
// When called from Begin() we don't have access to a proper version of the Hidden flag yet, so we replicate this code.
const bool will_be_visible = (window->DockIsActive && !window->DockTabIsVisible) ? false : true;
if ((window->Flags & ImGuiWindowFlags_DockNodeHost) && window->Viewport->LastFrameActive < g.FrameCount && will_be_visible)
{
// Steal/transfer ownership
//IMGUI_DEBUG_LOG("[%05d] Window '%s' steal Viewport %08X from Window '%s'\n", g.FrameCount, window->Name, window->Viewport->ID, window->Viewport->Window->Name);
window->Viewport->Window = window;
window->Viewport->ID = window->ID;
window->Viewport->LastNameHash = 0;
}
else if (!UpdateTryMergeWindowIntoHostViewport(window, g.Viewports[0])) // Merge?
{
// New viewport
window->Viewport = AddUpdateViewport(window, window->ID, window->Pos, window->Size, ImGuiViewportFlags_NoFocusOnAppearing);
}
}
// Regular (non-child, non-popup) windows by default are also allowed to protrude
// Child windows are kept contained within their parent.
else if (window->ViewportAllowPlatformMonitorExtend < 0 && (flags & ImGuiWindowFlags_ChildWindow) == 0)
window->ViewportAllowPlatformMonitorExtend = window->Viewport->PlatformMonitor;
// Update flags
window->ViewportOwned = (window == window->Viewport->Window);
// If the OS window has a title bar, hide our imgui title bar
//if (window->ViewportOwned && !(window->Viewport->Flags & ImGuiViewportFlags_NoDecoration))
// window->Flags |= ImGuiWindowFlags_NoTitleBar;
window->ViewportId = window->Viewport->ID;
}
// Called by user at the end of the main loop, after EndFrame()
// This will handle the creation/update of all OS windows via function defined in the ImGuiPlatformIO api.
void ImGui::UpdatePlatformWindows()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.FrameCountEnded == g.FrameCount && "Forgot to call Render() or EndFrame() before UpdatePlatformWindows()?");
IM_ASSERT(g.FrameCountPlatformEnded < g.FrameCount);
g.FrameCountPlatformEnded = g.FrameCount;
if (!(g.ConfigFlagsForFrame & ImGuiConfigFlags_ViewportsEnable))
return;
// Create/resize/destroy platform windows to match each active viewport.
// Skip the main viewport (index 0), which is always fully handled by the application!
for (int i = 1; i < g.Viewports.Size; i++)
{
ImGuiViewportP* viewport = g.Viewports[i];
// Destroy platform window if the viewport hasn't been submitted or if it is hosting a hidden window (the implicit/fallback Debug window will be registered its viewport then be disabled)
bool destroy_platform_window = false;
destroy_platform_window |= (viewport->LastFrameActive < g.FrameCount - 1);
destroy_platform_window |= (viewport->Window && !IsWindowActiveAndVisible(viewport->Window));
if (destroy_platform_window)
{
DestroyPlatformWindow(viewport);
continue;
}
// New windows that appears directly in a new viewport won't always have a size on their first frame
if (viewport->LastFrameActive < g.FrameCount || viewport->Size.x <= 0 || viewport->Size.y <= 0)
continue;
// Create window
bool is_new_platform_window = (viewport->PlatformWindowCreated == false);
if (is_new_platform_window)
{
//IMGUI_DEBUG_LOG("Create Platform Window %08X (%s)\n", viewport->ID, viewport->Window ? viewport->Window->Name : "n/a");
g.PlatformIO.Platform_CreateWindow(viewport);
if (g.PlatformIO.Renderer_CreateWindow != NULL)
g.PlatformIO.Renderer_CreateWindow(viewport);
viewport->LastNameHash = 0;
viewport->LastPlatformPos = viewport->LastPlatformSize = ImVec2(FLT_MAX, FLT_MAX); // By clearing those we'll enforce a call to Platform_SetWindowPos/Size below, before Platform_ShowWindow (FIXME: Is that necessary?)
viewport->LastRendererSize = viewport->Size; // We don't need to call Renderer_SetWindowSize() as it is expected Renderer_CreateWindow() already did it.
viewport->PlatformWindowCreated = true;
}
// Apply Position and Size (from ImGui to Platform/Renderer back-ends)
if ((viewport->LastPlatformPos.x != viewport->Pos.x || viewport->LastPlatformPos.y != viewport->Pos.y) && !viewport->PlatformRequestMove)
g.PlatformIO.Platform_SetWindowPos(viewport, viewport->Pos);
if ((viewport->LastPlatformSize.x != viewport->Size.x || viewport->LastPlatformSize.y != viewport->Size.y) && !viewport->PlatformRequestResize)
g.PlatformIO.Platform_SetWindowSize(viewport, viewport->Size);
if ((viewport->LastRendererSize.x != viewport->Size.x || viewport->LastRendererSize.y != viewport->Size.y) && g.PlatformIO.Renderer_SetWindowSize)
g.PlatformIO.Renderer_SetWindowSize(viewport, viewport->Size);
viewport->LastPlatformPos = viewport->Pos;
viewport->LastPlatformSize = viewport->LastRendererSize = viewport->Size;
// Update title bar (if it changed)
if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(viewport->Window))
{
const char* title_begin = window_for_title->Name;
char* title_end = (char*)(intptr_t)FindRenderedTextEnd(title_begin);
const ImGuiID title_hash = ImHashStr(title_begin, title_end - title_begin);
if (viewport->LastNameHash != title_hash)
{
char title_end_backup_c = *title_end;
*title_end = 0; // Cut existing buffer short instead of doing an alloc/free, no small gain.
g.PlatformIO.Platform_SetWindowTitle(viewport, title_begin);
*title_end = title_end_backup_c;
viewport->LastNameHash = title_hash;
}
}
// Update alpha (if it changed)
if (viewport->LastAlpha != viewport->Alpha && g.PlatformIO.Platform_SetWindowAlpha)
g.PlatformIO.Platform_SetWindowAlpha(viewport, viewport->Alpha);
viewport->LastAlpha = viewport->Alpha;
// Optional, general purpose call to allow the back-end to perform general book-keeping even if things haven't changed.
if (g.PlatformIO.Platform_UpdateWindow)
g.PlatformIO.Platform_UpdateWindow(viewport);
if (is_new_platform_window)
{
// On startup ensure new platform window don't steal focus (give it a few frames, as nested contents may lead to viewport being created a few frames late)
if (g.FrameCount < 3)
viewport->Flags |= ImGuiViewportFlags_NoFocusOnAppearing;
// Show window
g.PlatformIO.Platform_ShowWindow(viewport);
// Even without focus, we assume the window becomes front-most.
// This is useful for our platform z-order heuristic when io.MouseHoveredViewport is not available.
if (viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount)
viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount;
}
// Clear request flags
viewport->ClearRequestFlags();
}
// Update our implicit z-order knowledge of platform windows, which is used when the back-end cannot provide io.MouseHoveredViewport.
// When setting Platform_GetWindowFocus, it is expected that the platform back-end can handle calls without crashing if it doesn't have data stored.
if (g.PlatformIO.Platform_GetWindowFocus != NULL)
{
ImGuiViewportP* focused_viewport = NULL;
for (int n = 0; n < g.Viewports.Size && focused_viewport == NULL; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
if (n == 0 || viewport->PlatformWindowCreated)
if (g.PlatformIO.Platform_GetWindowFocus(viewport))
focused_viewport = viewport;
}
if (focused_viewport && g.PlatformLastFocusedViewport != focused_viewport->ID)
{
if (focused_viewport->LastFrontMostStampCount != g.WindowsFrontMostStampCount)
focused_viewport->LastFrontMostStampCount = ++g.WindowsFrontMostStampCount;
g.PlatformLastFocusedViewport = focused_viewport->ID;
}
}
}
// This is a default/basic function for performing the rendering/swap of multiple Platform Windows.
// Custom renderers may prefer to not call this function at all, and instead iterate the publicly exposed platform data and handle rendering/sync themselves.
// The Render/Swap functions stored in ImGuiPlatformIO are merely here to allow for this helper to exist, but you can do it yourself:
//
// ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
// for (int i = 1; i < platform_io.Viewports.Size; i++)
// MyRenderFunction(platform_io.Viewports[i], my_args);
// for (int i = 1; i < platform_io.Viewports.Size; i++)
// MySwapBufferFunction(platform_io.Viewports[i], my_args);
//
void ImGui::RenderPlatformWindowsDefault(void* platform_render_arg, void* renderer_render_arg)
{
// Skip the main viewport (index 0), which is always fully handled by the application!
ImGuiPlatformIO& platform_io = ImGui::GetPlatformIO();
for (int i = 1; i < platform_io.Viewports.Size; i++)
{
ImGuiViewport* viewport = platform_io.Viewports[i];
if (platform_io.Platform_RenderWindow) platform_io.Platform_RenderWindow(viewport, platform_render_arg);
if (platform_io.Renderer_RenderWindow) platform_io.Renderer_RenderWindow(viewport, renderer_render_arg);
}
for (int i = 1; i < platform_io.Viewports.Size; i++)
{
ImGuiViewport* viewport = platform_io.Viewports[i];
if (platform_io.Platform_SwapBuffers) platform_io.Platform_SwapBuffers(viewport, platform_render_arg);
if (platform_io.Renderer_SwapBuffers) platform_io.Renderer_SwapBuffers(viewport, renderer_render_arg);
}
}
static int ImGui::FindPlatformMonitorForPos(const ImVec2& pos)
{
ImGuiContext& g = *GImGui;
for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size; monitor_n++)
{
const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
if (ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize).Contains(pos))
return monitor_n;
}
return -1;
}
// Search for the monitor with the largest intersection area with the given rectangle
// We generally try to avoid searching loops but the monitor count should be very small here
static int ImGui::FindPlatformMonitorForRect(const ImRect& rect)
{
ImGuiContext& g = *GImGui;
// Use a minimum threshold of 1.0f so a zero-sized rect will still find its monitor given its position.
// This is necessary for tooltips which always resize down to zero at first.
const float surface_threshold = ImMax(rect.GetWidth() * rect.GetHeight() * 0.5f, 1.0f);
int best_monitor_n = -1;
float best_monitor_surface = 0.001f;
for (int monitor_n = 0; monitor_n < g.PlatformIO.Monitors.Size && best_monitor_surface < surface_threshold; monitor_n++)
{
const ImGuiPlatformMonitor& monitor = g.PlatformIO.Monitors[monitor_n];
const ImRect monitor_rect = ImRect(monitor.MainPos, monitor.MainPos + monitor.MainSize);
if (monitor_rect.Contains(rect))
return monitor_n;
ImRect overlapping_rect = rect;
overlapping_rect.ClipWithFull(monitor_rect);
float overlapping_surface = overlapping_rect.GetWidth() * overlapping_rect.GetHeight();
if (overlapping_surface < best_monitor_surface)
continue;
best_monitor_surface = overlapping_surface;
best_monitor_n = monitor_n;
}
return best_monitor_n;
}
void ImGui::DestroyPlatformWindow(ImGuiViewportP* viewport)
{
ImGuiContext& g = *GImGui;
if (g.PlatformIO.Renderer_DestroyWindow)
g.PlatformIO.Renderer_DestroyWindow(viewport);
if (g.PlatformIO.Platform_DestroyWindow)
g.PlatformIO.Platform_DestroyWindow(viewport);
IM_ASSERT(viewport->RendererUserData == NULL);
IM_ASSERT(viewport->PlatformUserData == NULL);
viewport->PlatformHandle = NULL;
viewport->RendererUserData = viewport->PlatformHandle = NULL;
viewport->PlatformWindowCreated = false;
viewport->ClearRequestFlags();
}
void ImGui::DestroyPlatformWindows()
{
// We call the destroy window on every viewport (including the main viewport, index 0) to give a chance to the back-end
// to clear any data they may have stored in e.g. PlatformUserData, RendererUserData.
// It is convenient for the platform back-end code to store something in the main viewport, in order for e.g. the mouse handling
// code to operator a consistent manner.
// It is expected that the back-end can handle calls to Renderer_DestroyWindow/Platform_DestroyWindow without
// crashing if it doesn't have data stored.
ImGuiContext& g = *GImGui;
for (int i = 0; i < g.Viewports.Size; i++)
DestroyPlatformWindow(g.Viewports[i]);
}
//-----------------------------------------------------------------------------
// [SECTION] KEYBOARD/GAMEPAD NAVIGATION
//-----------------------------------------------------------------------------
ImGuiDir ImGetDirQuadrantFromDelta(float dx, float dy)
{
if (ImFabs(dx) > ImFabs(dy))
return (dx > 0.0f) ? ImGuiDir_Right : ImGuiDir_Left;
return (dy > 0.0f) ? ImGuiDir_Down : ImGuiDir_Up;
}
static float inline NavScoreItemDistInterval(float a0, float a1, float b0, float b1)
{
if (a1 < b0)
return a1 - b0;
if (b1 < a0)
return a0 - b1;
return 0.0f;
}
static void inline NavClampRectToVisibleAreaForMoveDir(ImGuiDir move_dir, ImRect& r, const ImRect& clip_rect)
{
if (move_dir == ImGuiDir_Left || move_dir == ImGuiDir_Right)
{
r.Min.y = ImClamp(r.Min.y, clip_rect.Min.y, clip_rect.Max.y);
r.Max.y = ImClamp(r.Max.y, clip_rect.Min.y, clip_rect.Max.y);
}
else
{
r.Min.x = ImClamp(r.Min.x, clip_rect.Min.x, clip_rect.Max.x);
r.Max.x = ImClamp(r.Max.x, clip_rect.Min.x, clip_rect.Max.x);
}
}
// Scoring function for directional navigation. Based on https://gist.github.com/rygorous/6981057
static bool NavScoreItem(ImGuiNavMoveResult* result, ImRect cand)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (g.NavLayer != window->DC.NavLayerCurrent)
return false;
const ImRect& curr = g.NavScoringRectScreen; // Current modified source rect (NB: we've applied Max.x = Min.x in NavUpdate() to inhibit the effect of having varied item width)
g.NavScoringCount++;
// When entering through a NavFlattened border, we consider child window items as fully clipped for scoring
if (window->ParentWindow == g.NavWindow)
{
IM_ASSERT((window->Flags | g.NavWindow->Flags) & ImGuiWindowFlags_NavFlattened);
if (!window->ClipRect.Contains(cand))
return false;
cand.ClipWithFull(window->ClipRect); // This allows the scored item to not overlap other candidates in the parent window
}
// We perform scoring on items bounding box clipped by the current clipping rectangle on the other axis (clipping on our movement axis would give us equal scores for all clipped items)
// For example, this ensure that items in one column are not reached when moving vertically from items in another column.
NavClampRectToVisibleAreaForMoveDir(g.NavMoveClipDir, cand, window->ClipRect);
// Compute distance between boxes
// FIXME-NAV: Introducing biases for vertical navigation, needs to be removed.
float dbx = NavScoreItemDistInterval(cand.Min.x, cand.Max.x, curr.Min.x, curr.Max.x);
float dby = NavScoreItemDistInterval(ImLerp(cand.Min.y, cand.Max.y, 0.2f), ImLerp(cand.Min.y, cand.Max.y, 0.8f), ImLerp(curr.Min.y, curr.Max.y, 0.2f), ImLerp(curr.Min.y, curr.Max.y, 0.8f)); // Scale down on Y to keep using box-distance for vertically touching items
if (dby != 0.0f && dbx != 0.0f)
dbx = (dbx/1000.0f) + ((dbx > 0.0f) ? +1.0f : -1.0f);
float dist_box = ImFabs(dbx) + ImFabs(dby);
// Compute distance between centers (this is off by a factor of 2, but we only compare center distances with each other so it doesn't matter)
float dcx = (cand.Min.x + cand.Max.x) - (curr.Min.x + curr.Max.x);
float dcy = (cand.Min.y + cand.Max.y) - (curr.Min.y + curr.Max.y);
float dist_center = ImFabs(dcx) + ImFabs(dcy); // L1 metric (need this for our connectedness guarantee)
// Determine which quadrant of 'curr' our candidate item 'cand' lies in based on distance
ImGuiDir quadrant;
float dax = 0.0f, day = 0.0f, dist_axial = 0.0f;
if (dbx != 0.0f || dby != 0.0f)
{
// For non-overlapping boxes, use distance between boxes
dax = dbx;
day = dby;
dist_axial = dist_box;
quadrant = ImGetDirQuadrantFromDelta(dbx, dby);
}
else if (dcx != 0.0f || dcy != 0.0f)
{
// For overlapping boxes with different centers, use distance between centers
dax = dcx;
day = dcy;
dist_axial = dist_center;
quadrant = ImGetDirQuadrantFromDelta(dcx, dcy);
}
else
{
// Degenerate case: two overlapping buttons with same center, break ties arbitrarily (note that LastItemId here is really the _previous_ item order, but it doesn't matter)
quadrant = (window->DC.LastItemId < g.NavId) ? ImGuiDir_Left : ImGuiDir_Right;
}
#if IMGUI_DEBUG_NAV_SCORING
char buf[128];
if (ImGui::IsMouseHoveringRect(cand.Min, cand.Max))
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "dbox (%.2f,%.2f->%.4f)\ndcen (%.2f,%.2f->%.4f)\nd (%.2f,%.2f->%.4f)\nnav %c, quadrant %c", dbx, dby, dist_box, dcx, dcy, dist_center, dax, day, dist_axial, "WENS"[g.NavMoveDir], "WENS"[quadrant]);
ImDrawList* draw_list = ImGui::GetOverlayDrawList(window);
draw_list->AddRect(curr.Min, curr.Max, IM_COL32(255,200,0,100));
draw_list->AddRect(cand.Min, cand.Max, IM_COL32(255,255,0,200));
draw_list->AddRectFilled(cand.Max-ImVec2(4,4), cand.Max+ImGui::CalcTextSize(buf)+ImVec2(4,4), IM_COL32(40,0,0,150));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Max, ~0U, buf);
}
else if (g.IO.KeyCtrl) // Hold to preview score in matching quadrant. Press C to rotate.
{
if (ImGui::IsKeyPressedMap(ImGuiKey_C)) { g.NavMoveDirLast = (ImGuiDir)((g.NavMoveDirLast + 1) & 3); g.IO.KeysDownDuration[g.IO.KeyMap[ImGuiKey_C]] = 0.01f; }
if (quadrant == g.NavMoveDir)
{
ImFormatString(buf, IM_ARRAYSIZE(buf), "%.0f/%.0f", dist_box, dist_center);
ImDrawList* draw_list = ImGui::GetOverlayDrawList(window);
draw_list->AddRectFilled(cand.Min, cand.Max, IM_COL32(255, 0, 0, 200));
draw_list->AddText(g.IO.FontDefault, 13.0f, cand.Min, IM_COL32(255, 255, 255, 255), buf);
}
}
#endif
// Is it in the quadrant we're interesting in moving to?
bool new_best = false;
if (quadrant == g.NavMoveDir)
{
// Does it beat the current best candidate?
if (dist_box < result->DistBox)
{
result->DistBox = dist_box;
result->DistCenter = dist_center;
return true;
}
if (dist_box == result->DistBox)
{
// Try using distance between center points to break ties
if (dist_center < result->DistCenter)
{
result->DistCenter = dist_center;
new_best = true;
}
else if (dist_center == result->DistCenter)
{
// Still tied! we need to be extra-careful to make sure everything gets linked properly. We consistently break ties by symbolically moving "later" items
// (with higher index) to the right/downwards by an infinitesimal amount since we the current "best" button already (so it must have a lower index),
// this is fairly easy. This rule ensures that all buttons with dx==dy==0 will end up being linked in order of appearance along the x axis.
if (((g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down) ? dby : dbx) < 0.0f) // moving bj to the right/down decreases distance
new_best = true;
}
}
}
// Axial check: if 'curr' has no link at all in some direction and 'cand' lies roughly in that direction, add a tentative link. This will only be kept if no "real" matches
// are found, so it only augments the graph produced by the above method using extra links. (important, since it doesn't guarantee strong connectedness)
// This is just to avoid buttons having no links in a particular direction when there's a suitable neighbor. you get good graphs without this too.
// 2017/09/29: FIXME: This now currently only enabled inside menu bars, ideally we'd disable it everywhere. Menus in particular need to catch failure. For general navigation it feels awkward.
// Disabling it may lead to disconnected graphs when nodes are very spaced out on different axis. Perhaps consider offering this as an option?
if (result->DistBox == FLT_MAX && dist_axial < result->DistAxial) // Check axial match
if (g.NavLayer == 1 && !(g.NavWindow->Flags & ImGuiWindowFlags_ChildMenu))
if ((g.NavMoveDir == ImGuiDir_Left && dax < 0.0f) || (g.NavMoveDir == ImGuiDir_Right && dax > 0.0f) || (g.NavMoveDir == ImGuiDir_Up && day < 0.0f) || (g.NavMoveDir == ImGuiDir_Down && day > 0.0f))
{
result->DistAxial = dist_axial;
new_best = true;
}
return new_best;
}
// We get there when either NavId == id, or when g.NavAnyRequest is set (which is updated by NavUpdateAnyRequestFlag above)
static void ImGui::NavProcessItem(ImGuiWindow* window, const ImRect& nav_bb, const ImGuiID id)
{
ImGuiContext& g = *GImGui;
//if (!g.IO.NavActive) // [2017/10/06] Removed this possibly redundant test but I am not sure of all the side-effects yet. Some of the feature here will need to work regardless of using a _NoNavInputs flag.
// return;
const ImGuiItemFlags item_flags = window->DC.ItemFlags;
const ImRect nav_bb_rel(nav_bb.Min - window->Pos, nav_bb.Max - window->Pos);
// Process Init Request
if (g.NavInitRequest && g.NavLayer == window->DC.NavLayerCurrent)
{
// Even if 'ImGuiItemFlags_NoNavDefaultFocus' is on (typically collapse/close button) we record the first ResultId so they can be used as a fallback
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus) || g.NavInitResultId == 0)
{
g.NavInitResultId = id;
g.NavInitResultRectRel = nav_bb_rel;
}
if (!(item_flags & ImGuiItemFlags_NoNavDefaultFocus))
{
g.NavInitRequest = false; // Found a match, clear request
NavUpdateAnyRequestFlag();
}
}
// Process Move Request (scoring for navigation)
// FIXME-NAV: Consider policy for double scoring (scoring from NavScoringRectScreen + scoring from a rect wrapped according to current wrapping policy)
if ((g.NavId != id || (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AllowCurrentNavId)) && !(item_flags & ImGuiItemFlags_NoNav))
{
ImGuiNavMoveResult* result = (window == g.NavWindow) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
#if IMGUI_DEBUG_NAV_SCORING
// [DEBUG] Score all items in NavWindow at all times
if (!g.NavMoveRequest)
g.NavMoveDir = g.NavMoveDirLast;
bool new_best = NavScoreItem(result, nav_bb) && g.NavMoveRequest;
#else
bool new_best = g.NavMoveRequest && NavScoreItem(result, nav_bb);
#endif
if (new_best)
{
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
const float VISIBLE_RATIO = 0.70f;
if ((g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet) && window->ClipRect.Overlaps(nav_bb))
if (ImClamp(nav_bb.Max.y, window->ClipRect.Min.y, window->ClipRect.Max.y) - ImClamp(nav_bb.Min.y, window->ClipRect.Min.y, window->ClipRect.Max.y) >= (nav_bb.Max.y - nav_bb.Min.y) * VISIBLE_RATIO)
if (NavScoreItem(&g.NavMoveResultLocalVisibleSet, nav_bb))
{
result = &g.NavMoveResultLocalVisibleSet;
result->ID = id;
result->SelectScopeId = g.MultiSelectScopeId;
result->Window = window;
result->RectRel = nav_bb_rel;
}
}
// Update window-relative bounding box of navigated item
if (g.NavId == id)
{
g.NavWindow = window; // Always refresh g.NavWindow, because some operations such as FocusItem() don't have a window.
g.NavLayer = window->DC.NavLayerCurrent;
g.NavIdIsAlive = true;
g.NavIdTabCounter = window->FocusIdxTabCounter;
window->NavRectRel[window->DC.NavLayerCurrent] = nav_bb_rel; // Store item bounding box (relative to window position)
}
}
bool ImGui::NavMoveRequestButNoResultYet()
{
ImGuiContext& g = *GImGui;
return g.NavMoveRequest && g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0;
}
void ImGui::NavMoveRequestCancel()
{
ImGuiContext& g = *GImGui;
g.NavMoveRequest = false;
NavUpdateAnyRequestFlag();
}
void ImGui::NavMoveRequestForward(ImGuiDir move_dir, ImGuiDir clip_dir, const ImRect& bb_rel, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_None);
ImGui::NavMoveRequestCancel();
g.NavMoveDir = move_dir;
g.NavMoveClipDir = clip_dir;
g.NavMoveRequestForward = ImGuiNavForward_ForwardQueued;
g.NavMoveRequestFlags = move_flags;
g.NavWindow->NavRectRel[g.NavLayer] = bb_rel;
}
void ImGui::NavMoveRequestTryWrapping(ImGuiWindow* window, ImGuiNavMoveFlags move_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavWindow != window || !NavMoveRequestButNoResultYet() || g.NavMoveRequestForward != ImGuiNavForward_None || g.NavLayer != 0)
return;
IM_ASSERT(move_flags != 0); // No points calling this with no wrapping
ImRect bb_rel = window->NavRectRel[0];
ImGuiDir clip_dir = g.NavMoveDir;
if (g.NavMoveDir == ImGuiDir_Left && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = ImMax(window->SizeFull.x, window->SizeContents.x) - window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(-bb_rel.GetHeight()); clip_dir = ImGuiDir_Up; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Right && (move_flags & (ImGuiNavMoveFlags_WrapX | ImGuiNavMoveFlags_LoopX)))
{
bb_rel.Min.x = bb_rel.Max.x = -window->Scroll.x;
if (move_flags & ImGuiNavMoveFlags_WrapX) { bb_rel.TranslateY(+bb_rel.GetHeight()); clip_dir = ImGuiDir_Down; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Up && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = ImMax(window->SizeFull.y, window->SizeContents.y) - window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(-bb_rel.GetWidth()); clip_dir = ImGuiDir_Left; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
if (g.NavMoveDir == ImGuiDir_Down && (move_flags & (ImGuiNavMoveFlags_WrapY | ImGuiNavMoveFlags_LoopY)))
{
bb_rel.Min.y = bb_rel.Max.y = -window->Scroll.y;
if (move_flags & ImGuiNavMoveFlags_WrapY) { bb_rel.TranslateX(+bb_rel.GetWidth()); clip_dir = ImGuiDir_Right; }
NavMoveRequestForward(g.NavMoveDir, clip_dir, bb_rel, move_flags);
}
}
static void ImGui::NavSaveLastChildNavWindow(ImGuiWindow* nav_window)
{
ImGuiWindow* parent_window = nav_window;
while (parent_window && (parent_window->Flags & ImGuiWindowFlags_ChildWindow) != 0 && (parent_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
parent_window = parent_window->ParentWindow;
if (parent_window && parent_window != nav_window)
parent_window->NavLastChildNavWindow = nav_window;
}
// Call when we are expected to land on Layer 0 after FocusWindow()
static ImGuiWindow* ImGui::NavRestoreLastChildNavWindow(ImGuiWindow* window)
{
return window->NavLastChildNavWindow ? window->NavLastChildNavWindow : window;
}
static void NavRestoreLayer(ImGuiNavLayer layer)
{
ImGuiContext& g = *GImGui;
g.NavLayer = layer;
if (layer == 0)
g.NavWindow = ImGui::NavRestoreLastChildNavWindow(g.NavWindow);
if (g.NavWindow->NavLastIds[layer] != 0)
ImGui::SetNavIDWithRectRel(g.NavWindow->NavLastIds[layer], layer, g.NavWindow->NavRectRel[layer]);
else
ImGui::NavInitWindow(g.NavWindow, true);
}
static inline void ImGui::NavUpdateAnyRequestFlag()
{
ImGuiContext& g = *GImGui;
g.NavAnyRequest = g.NavMoveRequest || g.NavInitRequest || (IMGUI_DEBUG_NAV_SCORING && g.NavWindow != NULL);
if (g.NavAnyRequest)
IM_ASSERT(g.NavWindow != NULL);
}
// This needs to be called before we submit any widget (aka in or before Begin)
void ImGui::NavInitWindow(ImGuiWindow* window, bool force_reinit)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window == g.NavWindow);
bool init_for_nav = false;
if (!(window->Flags & ImGuiWindowFlags_NoNavInputs))
if (!(window->Flags & ImGuiWindowFlags_ChildWindow) || (window->Flags & ImGuiWindowFlags_Popup) || (window->NavLastIds[0] == 0) || force_reinit)
init_for_nav = true;
if (init_for_nav)
{
SetNavID(0, g.NavLayer);
g.NavInitRequest = true;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavInitResultRectRel = ImRect();
NavUpdateAnyRequestFlag();
}
else
{
g.NavId = window->NavLastIds[0];
}
}
static ImVec2 ImGui::NavCalcPreferredRefPos()
{
ImGuiContext& g = *GImGui;
if (g.NavDisableHighlight || !g.NavDisableMouseHover || !g.NavWindow)
{
// Mouse (we need a fallback in case the mouse becomes invalid after being used)
if (IsMousePosValid(&g.IO.MousePos))
return g.IO.MousePos;
return g.LastValidMousePos;
}
else
{
// When navigation is active and mouse is disabled, decide on an arbitrary position around the bottom left of the currently navigated item.
const ImRect& rect_rel = g.NavWindow->NavRectRel[g.NavLayer];
ImVec2 pos = g.NavWindow->Pos + ImVec2(rect_rel.Min.x + ImMin(g.Style.FramePadding.x * 4, rect_rel.GetWidth()), rect_rel.Max.y - ImMin(g.Style.FramePadding.y, rect_rel.GetHeight()));
ImRect visible_rect = g.NavWindow->Viewport->GetRect();
return ImFloor(ImClamp(pos, visible_rect.Min, visible_rect.Max)); // ImFloor() is important because non-integer mouse position application in back-end might be lossy and result in undesirable non-zero delta.
}
}
float ImGui::GetNavInputAmount(ImGuiNavInput n, ImGuiInputReadMode mode)
{
ImGuiContext& g = *GImGui;
if (mode == ImGuiInputReadMode_Down)
return g.IO.NavInputs[n]; // Instant, read analog input (0.0f..1.0f, as provided by user)
const float t = g.IO.NavInputsDownDuration[n];
if (t < 0.0f && mode == ImGuiInputReadMode_Released) // Return 1.0f when just released, no repeat, ignore analog input.
return (g.IO.NavInputsDownDurationPrev[n] >= 0.0f ? 1.0f : 0.0f);
if (t < 0.0f)
return 0.0f;
if (mode == ImGuiInputReadMode_Pressed) // Return 1.0f when just pressed, no repeat, ignore analog input.
return (t == 0.0f) ? 1.0f : 0.0f;
if (mode == ImGuiInputReadMode_Repeat)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.80f);
if (mode == ImGuiInputReadMode_RepeatSlow)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 1.00f, g.IO.KeyRepeatRate * 2.00f);
if (mode == ImGuiInputReadMode_RepeatFast)
return (float)CalcTypematicPressedRepeatAmount(t, t - g.IO.DeltaTime, g.IO.KeyRepeatDelay * 0.80f, g.IO.KeyRepeatRate * 0.30f);
return 0.0f;
}
ImVec2 ImGui::GetNavInputAmount2d(ImGuiNavDirSourceFlags dir_sources, ImGuiInputReadMode mode, float slow_factor, float fast_factor)
{
ImVec2 delta(0.0f, 0.0f);
if (dir_sources & ImGuiNavDirSourceFlags_Keyboard)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_KeyRight_, mode) - GetNavInputAmount(ImGuiNavInput_KeyLeft_, mode), GetNavInputAmount(ImGuiNavInput_KeyDown_, mode) - GetNavInputAmount(ImGuiNavInput_KeyUp_, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadDPad)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_DpadRight, mode) - GetNavInputAmount(ImGuiNavInput_DpadLeft, mode), GetNavInputAmount(ImGuiNavInput_DpadDown, mode) - GetNavInputAmount(ImGuiNavInput_DpadUp, mode));
if (dir_sources & ImGuiNavDirSourceFlags_PadLStick)
delta += ImVec2(GetNavInputAmount(ImGuiNavInput_LStickRight, mode) - GetNavInputAmount(ImGuiNavInput_LStickLeft, mode), GetNavInputAmount(ImGuiNavInput_LStickDown, mode) - GetNavInputAmount(ImGuiNavInput_LStickUp, mode));
if (slow_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakSlow))
delta *= slow_factor;
if (fast_factor != 0.0f && IsNavInputDown(ImGuiNavInput_TweakFast))
delta *= fast_factor;
return delta;
}
// Scroll to keep newly navigated item fully into view
// NB: We modify rect_rel by the amount we scrolled for, so it is immediately updated.
static void NavScrollToBringItemIntoView(ImGuiWindow* window, const ImRect& item_rect)
{
ImRect window_rect(window->InnerMainRect.Min - ImVec2(1, 1), window->InnerMainRect.Max + ImVec2(1, 1));
//GetOverlayDrawList(window)->AddRect(window_rect.Min, window_rect.Max, IM_COL32_WHITE); // [DEBUG]
if (window_rect.Contains(item_rect))
return;
ImGuiContext& g = *GImGui;
if (window->ScrollbarX && item_rect.Min.x < window_rect.Min.x)
{
window->ScrollTarget.x = item_rect.Min.x - window->Pos.x + window->Scroll.x - g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 0.0f;
}
else if (window->ScrollbarX && item_rect.Max.x >= window_rect.Max.x)
{
window->ScrollTarget.x = item_rect.Max.x - window->Pos.x + window->Scroll.x + g.Style.ItemSpacing.x;
window->ScrollTargetCenterRatio.x = 1.0f;
}
if (item_rect.Min.y < window_rect.Min.y)
{
window->ScrollTarget.y = item_rect.Min.y - window->Pos.y + window->Scroll.y - g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 0.0f;
}
else if (item_rect.Max.y >= window_rect.Max.y)
{
window->ScrollTarget.y = item_rect.Max.y - window->Pos.y + window->Scroll.y + g.Style.ItemSpacing.y;
window->ScrollTargetCenterRatio.y = 1.0f;
}
}
static void ImGui::NavUpdate()
{
ImGuiContext& g = *GImGui;
g.IO.WantSetMousePos = false;
#if 0
if (g.NavScoringCount > 0) IMGUI_DEBUG_LOG("NavScoringCount %d for '%s' layer %d (Init:%d, Move:%d)\n", g.FrameCount, g.NavScoringCount, g.NavWindow ? g.NavWindow->Name : "NULL", g.NavLayer, g.NavInitRequest || g.NavInitResultId != 0, g.NavMoveRequest);
#endif
// Set input source as Gamepad when buttons are pressed before we map Keyboard (some features differs when used with Gamepad vs Keyboard)
bool nav_keyboard_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard) != 0;
bool nav_gamepad_active = (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableGamepad) != 0 && (g.IO.BackendFlags & ImGuiBackendFlags_HasGamepad) != 0;
if (nav_gamepad_active)
if (g.IO.NavInputs[ImGuiNavInput_Activate] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Input] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Cancel] > 0.0f || g.IO.NavInputs[ImGuiNavInput_Menu] > 0.0f)
g.NavInputSource = ImGuiInputSource_NavGamepad;
// Update Keyboard->Nav inputs mapping
if (nav_keyboard_active)
{
#define NAV_MAP_KEY(_KEY, _NAV_INPUT) if (IsKeyDown(g.IO.KeyMap[_KEY])) { g.IO.NavInputs[_NAV_INPUT] = 1.0f; g.NavInputSource = ImGuiInputSource_NavKeyboard; }
NAV_MAP_KEY(ImGuiKey_Space, ImGuiNavInput_Activate );
NAV_MAP_KEY(ImGuiKey_Enter, ImGuiNavInput_Input );
NAV_MAP_KEY(ImGuiKey_Escape, ImGuiNavInput_Cancel );
NAV_MAP_KEY(ImGuiKey_LeftArrow, ImGuiNavInput_KeyLeft_ );
NAV_MAP_KEY(ImGuiKey_RightArrow,ImGuiNavInput_KeyRight_);
NAV_MAP_KEY(ImGuiKey_UpArrow, ImGuiNavInput_KeyUp_ );
NAV_MAP_KEY(ImGuiKey_DownArrow, ImGuiNavInput_KeyDown_ );
if (g.IO.KeyCtrl) g.IO.NavInputs[ImGuiNavInput_TweakSlow] = 1.0f;
if (g.IO.KeyShift) g.IO.NavInputs[ImGuiNavInput_TweakFast] = 1.0f;
if (g.IO.KeyAlt) g.IO.NavInputs[ImGuiNavInput_KeyMenu_] = 1.0f;
#undef NAV_MAP_KEY
}
memcpy(g.IO.NavInputsDownDurationPrev, g.IO.NavInputsDownDuration, sizeof(g.IO.NavInputsDownDuration));
for (int i = 0; i < IM_ARRAYSIZE(g.IO.NavInputs); i++)
g.IO.NavInputsDownDuration[i] = (g.IO.NavInputs[i] > 0.0f) ? (g.IO.NavInputsDownDuration[i] < 0.0f ? 0.0f : g.IO.NavInputsDownDuration[i] + g.IO.DeltaTime) : -1.0f;
// Process navigation init request (select first/default focus)
if (g.NavInitResultId != 0 && (!g.NavDisableHighlight || g.NavInitRequestFromMove))
{
// Apply result from previous navigation init request (will typically select the first item, unless SetItemDefaultFocus() has been called)
IM_ASSERT(g.NavWindow);
if (g.NavInitRequestFromMove)
SetNavIDWithRectRel(g.NavInitResultId, g.NavLayer, g.NavInitResultRectRel);
else
SetNavID(g.NavInitResultId, g.NavLayer);
g.NavWindow->NavRectRel[g.NavLayer] = g.NavInitResultRectRel;
}
g.NavInitRequest = false;
g.NavInitRequestFromMove = false;
g.NavInitResultId = 0;
g.NavJustMovedToId = 0;
// Process navigation move request
if (g.NavMoveRequest)
NavUpdateMoveResult();
// When a forwarded move request failed, we restore the highlight that we disabled during the forward frame
if (g.NavMoveRequestForward == ImGuiNavForward_ForwardActive)
{
IM_ASSERT(g.NavMoveRequest);
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
g.NavDisableHighlight = false;
g.NavMoveRequestForward = ImGuiNavForward_None;
}
// Apply application mouse position movement, after we had a chance to process move request result.
if (g.NavMousePosDirty && g.NavIdIsAlive)
{
// Set mouse position given our knowledge of the navigated item position from last frame
if ((g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableSetMousePos) && (g.IO.BackendFlags & ImGuiBackendFlags_HasSetMousePos))
{
if (!g.NavDisableHighlight && g.NavDisableMouseHover && g.NavWindow)
{
g.IO.MousePos = g.IO.MousePosPrev = NavCalcPreferredRefPos();
g.IO.WantSetMousePos = true;
}
}
g.NavMousePosDirty = false;
}
g.NavIdIsAlive = false;
g.NavJustTabbedId = 0;
IM_ASSERT(g.NavLayer == 0 || g.NavLayer == 1);
// Store our return window (for returning from Layer 1 to Layer 0) and clear it as soon as we step back in our own Layer 0
if (g.NavWindow)
NavSaveLastChildNavWindow(g.NavWindow);
if (g.NavWindow && g.NavWindow->NavLastChildNavWindow != NULL && g.NavLayer == 0)
g.NavWindow->NavLastChildNavWindow = NULL;
// Update CTRL+TAB and Windowing features (hold Square to move/resize/etc.)
NavUpdateWindowing();
// Set output flags for user application
g.IO.NavActive = (nav_keyboard_active || nav_gamepad_active) && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs);
g.IO.NavVisible = (g.IO.NavActive && g.NavId != 0 && !g.NavDisableHighlight) || (g.NavWindowingTarget != NULL);
// Process NavCancel input (to close a popup, get back to parent, clear focus)
if (IsNavInputPressed(ImGuiNavInput_Cancel, ImGuiInputReadMode_Pressed))
{
if (g.ActiveId != 0)
{
if (!(g.ActiveIdBlockNavInputFlags & (1 << ImGuiNavInput_Cancel)))
ClearActiveID();
}
else if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow) && !(g.NavWindow->Flags & ImGuiWindowFlags_Popup) && g.NavWindow->ParentWindow && g.NavWindow != g.NavWindow->RootWindowDockStop)
{
// Exit child window
ImGuiWindow* child_window = g.NavWindow;
ImGuiWindow* parent_window = g.NavWindow->ParentWindow;
IM_ASSERT(child_window->ChildId != 0);
FocusWindow(parent_window);
SetNavID(child_window->ChildId, 0);
g.NavIdIsAlive = false;
if (g.NavDisableMouseHover)
g.NavMousePosDirty = true;
}
else if (g.OpenPopupStack.Size > 0)
{
// Close open popup/menu
if (!(g.OpenPopupStack.back().Window->Flags & ImGuiWindowFlags_Modal))
ClosePopupToLevel(g.OpenPopupStack.Size - 1, true);
}
else if (g.NavLayer != 0)
{
// Leave the "menu" layer
NavRestoreLayer(ImGuiNavLayer_Main);
}
else
{
// Clear NavLastId for popups but keep it for regular child window so we can leave one and come back where we were
if (g.NavWindow && ((g.NavWindow->Flags & ImGuiWindowFlags_Popup) || !(g.NavWindow->Flags & ImGuiWindowFlags_ChildWindow)))
g.NavWindow->NavLastIds[0] = 0;
g.NavId = 0;
}
}
// Process manual activation request
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = 0;
if (g.NavId != 0 && !g.NavDisableHighlight && !g.NavWindowingTarget && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
bool activate_down = IsNavInputDown(ImGuiNavInput_Activate);
bool activate_pressed = activate_down && IsNavInputPressed(ImGuiNavInput_Activate, ImGuiInputReadMode_Pressed);
if (g.ActiveId == 0 && activate_pressed)
g.NavActivateId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_down)
g.NavActivateDownId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && activate_pressed)
g.NavActivatePressedId = g.NavId;
if ((g.ActiveId == 0 || g.ActiveId == g.NavId) && IsNavInputPressed(ImGuiNavInput_Input, ImGuiInputReadMode_Pressed))
g.NavInputId = g.NavId;
}
if (g.NavWindow && (g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
g.NavDisableHighlight = true;
if (g.NavActivateId != 0)
IM_ASSERT(g.NavActivateDownId == g.NavActivateId);
g.NavMoveRequest = false;
// Process programmatic activation request
if (g.NavNextActivateId != 0)
g.NavActivateId = g.NavActivateDownId = g.NavActivatePressedId = g.NavInputId = g.NavNextActivateId;
g.NavNextActivateId = 0;
// Initiate directional inputs request
const int allowed_dir_flags = (g.ActiveId == 0) ? ~0 : g.ActiveIdAllowNavDirFlags;
if (g.NavMoveRequestForward == ImGuiNavForward_None)
{
g.NavMoveDir = ImGuiDir_None;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_None;
if (g.NavWindow && !g.NavWindowingTarget && allowed_dir_flags && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs))
{
if ((allowed_dir_flags & (1<<ImGuiDir_Left)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadLeft, ImGuiNavInput_KeyLeft_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Left;
if ((allowed_dir_flags & (1<<ImGuiDir_Right)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadRight,ImGuiNavInput_KeyRight_,ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Right;
if ((allowed_dir_flags & (1<<ImGuiDir_Up)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadUp, ImGuiNavInput_KeyUp_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Up;
if ((allowed_dir_flags & (1<<ImGuiDir_Down)) && IsNavInputPressedAnyOfTwo(ImGuiNavInput_DpadDown, ImGuiNavInput_KeyDown_, ImGuiInputReadMode_Repeat)) g.NavMoveDir = ImGuiDir_Down;
}
g.NavMoveClipDir = g.NavMoveDir;
}
else
{
// Forwarding previous request (which has been modified, e.g. wrap around menus rewrite the requests with a starting rectangle at the other side of the window)
// (Preserve g.NavMoveRequestFlags, g.NavMoveClipDir which were set by the NavMoveRequestForward() function)
IM_ASSERT(g.NavMoveDir != ImGuiDir_None && g.NavMoveClipDir != ImGuiDir_None);
IM_ASSERT(g.NavMoveRequestForward == ImGuiNavForward_ForwardQueued);
g.NavMoveRequestForward = ImGuiNavForward_ForwardActive;
}
// Update PageUp/PageDown scroll
float nav_scoring_rect_offset_y = 0.0f;
if (nav_keyboard_active)
nav_scoring_rect_offset_y = NavUpdatePageUpPageDown(allowed_dir_flags);
// If we initiate a movement request and have no current NavId, we initiate a InitDefautRequest that will be used as a fallback if the direction fails to find a match
if (g.NavMoveDir != ImGuiDir_None)
{
g.NavMoveRequest = true;
g.NavMoveDirLast = g.NavMoveDir;
}
if (g.NavMoveRequest && g.NavId == 0)
{
g.NavInitRequest = g.NavInitRequestFromMove = true;
g.NavInitResultId = 0;
g.NavDisableHighlight = false;
}
NavUpdateAnyRequestFlag();
// Scrolling
if (g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget)
{
// *Fallback* manual-scroll with Nav directional keys when window has no navigable item
ImGuiWindow* window = g.NavWindow;
const float scroll_speed = ImFloor(window->CalcFontSize() * 100 * g.IO.DeltaTime + 0.5f); // We need round the scrolling speed because sub-pixel scroll isn't reliably supported.
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll && g.NavMoveRequest)
{
if (g.NavMoveDir == ImGuiDir_Left || g.NavMoveDir == ImGuiDir_Right)
SetWindowScrollX(window, ImFloor(window->Scroll.x + ((g.NavMoveDir == ImGuiDir_Left) ? -1.0f : +1.0f) * scroll_speed));
if (g.NavMoveDir == ImGuiDir_Up || g.NavMoveDir == ImGuiDir_Down)
SetWindowScrollY(window, ImFloor(window->Scroll.y + ((g.NavMoveDir == ImGuiDir_Up) ? -1.0f : +1.0f) * scroll_speed));
}
// *Normal* Manual scroll with NavScrollXXX keys
// Next movement request will clamp the NavId reference rectangle to the visible area, so navigation will resume within those bounds.
ImVec2 scroll_dir = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down, 1.0f/10.0f, 10.0f);
if (scroll_dir.x != 0.0f && window->ScrollbarX)
{
SetWindowScrollX(window, ImFloor(window->Scroll.x + scroll_dir.x * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
if (scroll_dir.y != 0.0f)
{
SetWindowScrollY(window, ImFloor(window->Scroll.y + scroll_dir.y * scroll_speed));
g.NavMoveFromClampedRefRect = true;
}
}
// Reset search results
g.NavMoveResultLocal.Clear();
g.NavMoveResultLocalVisibleSet.Clear();
g.NavMoveResultOther.Clear();
// When we have manually scrolled (without using navigation) and NavId becomes out of bounds, we project its bounding box to the visible area to restart navigation within visible items
if (g.NavMoveRequest && g.NavMoveFromClampedRefRect && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
ImRect window_rect_rel(window->InnerMainRect.Min - window->Pos - ImVec2(1,1), window->InnerMainRect.Max - window->Pos + ImVec2(1,1));
if (!window_rect_rel.Contains(window->NavRectRel[g.NavLayer]))
{
float pad = window->CalcFontSize() * 0.5f;
window_rect_rel.Expand(ImVec2(-ImMin(window_rect_rel.GetWidth(), pad), -ImMin(window_rect_rel.GetHeight(), pad))); // Terrible approximation for the intent of starting navigation from first fully visible item
window->NavRectRel[g.NavLayer].ClipWith(window_rect_rel);
g.NavId = 0;
}
g.NavMoveFromClampedRefRect = false;
}
// For scoring we use a single segment on the left side our current item bounding box (not touching the edge to avoid box overlap with zero-spaced items)
ImRect nav_rect_rel = (g.NavWindow && !g.NavWindow->NavRectRel[g.NavLayer].IsInverted()) ? g.NavWindow->NavRectRel[g.NavLayer] : ImRect(0,0,0,0);
g.NavScoringRectScreen = g.NavWindow ? ImRect(g.NavWindow->Pos + nav_rect_rel.Min, g.NavWindow->Pos + nav_rect_rel.Max) : ImRect(0,0,0,0);
g.NavScoringRectScreen.TranslateY(nav_scoring_rect_offset_y);
g.NavScoringRectScreen.Min.x = ImMin(g.NavScoringRectScreen.Min.x + 1.0f, g.NavScoringRectScreen.Max.x);
g.NavScoringRectScreen.Max.x = g.NavScoringRectScreen.Min.x;
IM_ASSERT(!g.NavScoringRectScreen.IsInverted()); // Ensure if we have a finite, non-inverted bounding box here will allows us to remove extraneous ImFabs() calls in NavScoreItem().
//g.OverlayDrawList.AddRect(g.NavScoringRectScreen.Min, g.NavScoringRectScreen.Max, IM_COL32(255,200,0,255)); // [DEBUG]
g.NavScoringCount = 0;
#if IMGUI_DEBUG_NAV_RECTS
if (g.NavWindow) { for (int layer = 0; layer < 2; layer++) GetOverlayDrawList(g.NavWindow)->AddRect(g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Min, g.NavWindow->Pos + g.NavWindow->NavRectRel[layer].Max, IM_COL32(255,200,0,255)); } // [DEBUG]
if (g.NavWindow) { ImU32 col = (!g.NavWindow->Hidden) ? IM_COL32(255,0,255,255) : IM_COL32(255,0,0,255); ImVec2 p = NavCalcPreferredRefPos(); char buf[32]; ImFormatString(buf, 32, "%d", g.NavLayer); GetOverlayDrawList(g.NavWindow)->AddCircleFilled(p, 3.0f, col); GetOverlayDrawList(g.NavWindow)->AddText(NULL, 13.0f, p + ImVec2(8,-4), col, buf); }
#endif
}
// Apply result from previous frame navigation directional move request
static void ImGui::NavUpdateMoveResult()
{
ImGuiContext& g = *GImGui;
if (g.NavMoveResultLocal.ID == 0 && g.NavMoveResultOther.ID == 0)
{
// In a situation when there is no results but NavId != 0, re-enable the Navigation highlight (because g.NavId is not considered as a possible result)
if (g.NavId != 0)
{
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
}
return;
}
// Select which result to use
ImGuiNavMoveResult* result = (g.NavMoveResultLocal.ID != 0) ? &g.NavMoveResultLocal : &g.NavMoveResultOther;
// PageUp/PageDown behavior first jumps to the bottom/top mostly visible item, _otherwise_ use the result from the previous/next page.
if (g.NavMoveRequestFlags & ImGuiNavMoveFlags_AlsoScoreVisibleSet)
if (g.NavMoveResultLocalVisibleSet.ID != 0 && g.NavMoveResultLocalVisibleSet.ID != g.NavId)
result = &g.NavMoveResultLocalVisibleSet;
// Maybe entering a flattened child from the outside? In this case solve the tie using the regular scoring rules.
if (result != &g.NavMoveResultOther && g.NavMoveResultOther.ID != 0 && g.NavMoveResultOther.Window->ParentWindow == g.NavWindow)
if ((g.NavMoveResultOther.DistBox < result->DistBox) || (g.NavMoveResultOther.DistBox == result->DistBox && g.NavMoveResultOther.DistCenter < result->DistCenter))
result = &g.NavMoveResultOther;
IM_ASSERT(g.NavWindow && result->Window);
// Scroll to keep newly navigated item fully into view.
if (g.NavLayer == 0)
{
ImRect rect_abs = ImRect(result->RectRel.Min + result->Window->Pos, result->RectRel.Max + result->Window->Pos);
NavScrollToBringItemIntoView(result->Window, rect_abs);
// Estimate upcoming scroll so we can offset our result position so mouse position can be applied immediately after in NavUpdate()
ImVec2 next_scroll = CalcNextScrollFromScrollTargetAndClamp(result->Window, false);
ImVec2 delta_scroll = result->Window->Scroll - next_scroll;
result->RectRel.Translate(delta_scroll);
// Also scroll parent window to keep us into view if necessary (we could/should technically recurse back the whole the parent hierarchy).
if (result->Window->Flags & ImGuiWindowFlags_ChildWindow)
NavScrollToBringItemIntoView(result->Window->ParentWindow, ImRect(rect_abs.Min + delta_scroll, rect_abs.Max + delta_scroll));
}
ClearActiveID();
g.NavWindow = result->Window;
if (g.NavId != result->ID)
{
// Don't set NavJustMovedToId if just landed on the same spot (which may happen with ImGuiNavMoveFlags_AllowCurrentNavId)
g.NavJustMovedToId = result->ID;
g.NavJustMovedToSelectScopeId = result->SelectScopeId;
}
SetNavIDWithRectRel(result->ID, g.NavLayer, result->RectRel);
g.NavMoveFromClampedRefRect = false;
}
static float ImGui::NavUpdatePageUpPageDown(int allowed_dir_flags)
{
ImGuiContext& g = *GImGui;
if (g.NavMoveDir == ImGuiDir_None && g.NavWindow && !(g.NavWindow->Flags & ImGuiWindowFlags_NoNavInputs) && !g.NavWindowingTarget && g.NavLayer == 0)
{
ImGuiWindow* window = g.NavWindow;
bool page_up_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageUp]) && (allowed_dir_flags & (1 << ImGuiDir_Up));
bool page_down_held = IsKeyDown(g.IO.KeyMap[ImGuiKey_PageDown]) && (allowed_dir_flags & (1 << ImGuiDir_Down));
if (page_up_held != page_down_held) // If either (not both) are pressed
{
if (window->DC.NavLayerActiveMask == 0x00 && window->DC.NavHasScroll)
{
// Fallback manual-scroll when window has no navigable item
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
SetWindowScrollY(window, window->Scroll.y - window->InnerClipRect.GetHeight());
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
SetWindowScrollY(window, window->Scroll.y + window->InnerClipRect.GetHeight());
}
else
{
const ImRect& nav_rect_rel = window->NavRectRel[g.NavLayer];
const float page_offset_y = ImMax(0.0f, window->InnerClipRect.GetHeight() - window->CalcFontSize() * 1.0f + nav_rect_rel.GetHeight());
float nav_scoring_rect_offset_y = 0.0f;
if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageUp], true))
{
nav_scoring_rect_offset_y = -page_offset_y;
g.NavMoveDir = ImGuiDir_Down; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Up;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
else if (IsKeyPressed(g.IO.KeyMap[ImGuiKey_PageDown], true))
{
nav_scoring_rect_offset_y = +page_offset_y;
g.NavMoveDir = ImGuiDir_Up; // Because our scoring rect is offset, we intentionally request the opposite direction (so we can always land on the last item)
g.NavMoveClipDir = ImGuiDir_Down;
g.NavMoveRequestFlags = ImGuiNavMoveFlags_AllowCurrentNavId | ImGuiNavMoveFlags_AlsoScoreVisibleSet;
}
return nav_scoring_rect_offset_y;
}
}
}
return 0.0f;
}
static int FindWindowFocusIndex(ImGuiWindow* window) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = g.WindowsFocusOrder.Size-1; i >= 0; i--)
if (g.WindowsFocusOrder[i] == window)
return i;
return -1;
}
static ImGuiWindow* FindWindowNavFocusable(int i_start, int i_stop, int dir) // FIXME-OPT O(N)
{
ImGuiContext& g = *GImGui;
for (int i = i_start; i >= 0 && i < g.WindowsFocusOrder.Size && i != i_stop; i += dir)
if (ImGui::IsWindowNavFocusable(g.WindowsFocusOrder[i]))
return g.WindowsFocusOrder[i];
return NULL;
}
static void NavUpdateWindowingHighlightWindow(int focus_change_dir)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget);
if (g.NavWindowingTarget->Flags & ImGuiWindowFlags_Modal)
return;
const int i_current = FindWindowFocusIndex(g.NavWindowingTarget);
ImGuiWindow* window_target = FindWindowNavFocusable(i_current + focus_change_dir, -INT_MAX, focus_change_dir);
if (!window_target)
window_target = FindWindowNavFocusable((focus_change_dir < 0) ? (g.WindowsFocusOrder.Size - 1) : 0, i_current, focus_change_dir);
if (window_target) // Don't reset windowing target if there's a single window in the list
g.NavWindowingTarget = g.NavWindowingTargetAnim = window_target;
g.NavWindowingToggleLayer = false;
}
// Window management mode (hold to: change focus/move/resize, tap to: toggle menu layer)
static void ImGui::NavUpdateWindowing()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* apply_focus_window = NULL;
bool apply_toggle_layer = false;
ImGuiWindow* modal_window = GetFrontMostPopupModal();
if (modal_window != NULL)
{
g.NavWindowingTarget = NULL;
return;
}
// Fade out
if (g.NavWindowingTargetAnim && g.NavWindowingTarget == NULL)
{
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha - g.IO.DeltaTime * 10.0f, 0.0f);
if (g.DimBgRatio <= 0.0f && g.NavWindowingHighlightAlpha <= 0.0f)
g.NavWindowingTargetAnim = NULL;
}
// Start CTRL-TAB or Square+L/R window selection
bool start_windowing_with_gamepad = !g.NavWindowingTarget && IsNavInputPressed(ImGuiNavInput_Menu, ImGuiInputReadMode_Pressed);
bool start_windowing_with_keyboard = !g.NavWindowingTarget && g.IO.KeyCtrl && IsKeyPressedMap(ImGuiKey_Tab) && (g.IO.ConfigFlags & ImGuiConfigFlags_NavEnableKeyboard);
if (start_windowing_with_gamepad || start_windowing_with_keyboard)
if (ImGuiWindow* window = g.NavWindow ? g.NavWindow : FindWindowNavFocusable(g.WindowsFocusOrder.Size - 1, -INT_MAX, -1))
{
g.NavWindowingTarget = g.NavWindowingTargetAnim = window;
g.NavWindowingTimer = g.NavWindowingHighlightAlpha = 0.0f;
g.NavWindowingToggleLayer = start_windowing_with_keyboard ? false : true;
g.NavInputSource = start_windowing_with_keyboard ? ImGuiInputSource_NavKeyboard : ImGuiInputSource_NavGamepad;
}
// Gamepad update
g.NavWindowingTimer += g.IO.DeltaTime;
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavGamepad)
{
// Highlight only appears after a brief time holding the button, so that a fast tap on PadMenu (to toggle NavLayer) doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f));
// Select window to focus
const int focus_change_dir = (int)IsNavInputPressed(ImGuiNavInput_FocusPrev, ImGuiInputReadMode_RepeatSlow) - (int)IsNavInputPressed(ImGuiNavInput_FocusNext, ImGuiInputReadMode_RepeatSlow);
if (focus_change_dir != 0)
{
NavUpdateWindowingHighlightWindow(focus_change_dir);
g.NavWindowingHighlightAlpha = 1.0f;
}
// Single press toggles NavLayer, long press with L/R apply actual focus on release (until then the window was merely rendered front-most)
if (!IsNavInputDown(ImGuiNavInput_Menu))
{
g.NavWindowingToggleLayer &= (g.NavWindowingHighlightAlpha < 1.0f); // Once button was held long enough we don't consider it a tap-to-toggle-layer press anymore.
if (g.NavWindowingToggleLayer && g.NavWindow)
apply_toggle_layer = true;
else if (!g.NavWindowingToggleLayer)
apply_focus_window = g.NavWindowingTarget;
g.NavWindowingTarget = NULL;
}
}
// Keyboard: Focus
if (g.NavWindowingTarget && g.NavInputSource == ImGuiInputSource_NavKeyboard)
{
// Visuals only appears after a brief time after pressing TAB the first time, so that a fast CTRL+TAB doesn't add visual noise
g.NavWindowingHighlightAlpha = ImMax(g.NavWindowingHighlightAlpha, ImSaturate((g.NavWindowingTimer - NAV_WINDOWING_HIGHLIGHT_DELAY) / 0.05f)); // 1.0f
if (IsKeyPressedMap(ImGuiKey_Tab, true))
NavUpdateWindowingHighlightWindow(g.IO.KeyShift ? +1 : -1);
if (!g.IO.KeyCtrl)
apply_focus_window = g.NavWindowingTarget;
}
// Keyboard: Press and Release ALT to toggle menu layer
// FIXME: We lack an explicit IO variable for "is the imgui window focused", so compare mouse validity to detect the common case of back-end clearing releases all keys on ALT-TAB
if (IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Pressed))
g.NavWindowingToggleLayer = true;
if ((g.ActiveId == 0 || g.ActiveIdAllowOverlap) && g.NavWindowingToggleLayer && IsNavInputPressed(ImGuiNavInput_KeyMenu_, ImGuiInputReadMode_Released))
if (IsMousePosValid(&g.IO.MousePos) == IsMousePosValid(&g.IO.MousePosPrev))
apply_toggle_layer = true;
// Move window
if (g.NavWindowingTarget && !(g.NavWindowingTarget->Flags & ImGuiWindowFlags_NoMove))
{
ImVec2 move_delta;
if (g.NavInputSource == ImGuiInputSource_NavKeyboard && !g.IO.KeyShift)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_Keyboard, ImGuiInputReadMode_Down);
if (g.NavInputSource == ImGuiInputSource_NavGamepad)
move_delta = GetNavInputAmount2d(ImGuiNavDirSourceFlags_PadLStick, ImGuiInputReadMode_Down);
if (move_delta.x != 0.0f || move_delta.y != 0.0f)
{
const float NAV_MOVE_SPEED = 800.0f;
const float move_speed = ImFloor(NAV_MOVE_SPEED * g.IO.DeltaTime * ImMin(g.IO.DisplayFramebufferScale.x, g.IO.DisplayFramebufferScale.y)); // FIXME: Doesn't code variable framerate very well
g.NavWindowingTarget->RootWindow->Pos += move_delta * move_speed;
g.NavDisableMouseHover = true;
MarkIniSettingsDirty(g.NavWindowingTarget);
}
}
// Apply final focus
if (apply_focus_window && (g.NavWindow == NULL || apply_focus_window != g.NavWindow->RootWindowDockStop))
{
ImGuiViewport* previous_viewport = g.NavWindow ? g.NavWindow->Viewport : NULL;
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
apply_focus_window = NavRestoreLastChildNavWindow(apply_focus_window);
ClosePopupsOverWindow(apply_focus_window);
FocusWindow(apply_focus_window);
if (apply_focus_window->NavLastIds[0] == 0)
NavInitWindow(apply_focus_window, false);
// If the window only has a menu layer, select it directly
if (apply_focus_window->DC.NavLayerActiveMask == (1 << ImGuiNavLayer_Menu))
g.NavLayer = ImGuiNavLayer_Menu;
// Request OS level focus
if (apply_focus_window->Viewport != previous_viewport && g.PlatformIO.Platform_SetWindowFocus)
g.PlatformIO.Platform_SetWindowFocus(apply_focus_window->Viewport);
}
if (apply_focus_window)
g.NavWindowingTarget = NULL;
// Apply menu/layer toggle
if (apply_toggle_layer && g.NavWindow)
{
// Move to parent menu if necessary
ImGuiWindow* new_nav_window = g.NavWindow;
while (new_nav_window->ParentWindow
&& (new_nav_window->DC.NavLayerActiveMask & (1 << 1)) == 0
&& (new_nav_window->Flags & ImGuiWindowFlags_ChildWindow) != 0
&& (new_nav_window->Flags & (ImGuiWindowFlags_Popup | ImGuiWindowFlags_ChildMenu)) == 0)
new_nav_window = new_nav_window->ParentWindow;
if (new_nav_window != g.NavWindow)
{
ImGuiWindow* old_nav_window = g.NavWindow;
FocusWindow(new_nav_window);
new_nav_window->NavLastChildNavWindow = old_nav_window;
}
g.NavDisableHighlight = false;
g.NavDisableMouseHover = true;
// When entering a regular menu bar with the Alt key, we always reinitialize the navigation ID. It however persist on docking tab tabs.
const ImGuiNavLayer new_nav_layer = (g.NavWindow->DC.NavLayerActiveMask & (1 << ImGuiNavLayer_Menu)) ? (ImGuiNavLayer)((int)g.NavLayer ^ 1) : ImGuiNavLayer_Main;
const bool preserve_layer_1_nav_id = (new_nav_window->DockNodeAsHost != NULL);
if (new_nav_layer == ImGuiNavLayer_Menu && !preserve_layer_1_nav_id)
g.NavWindow->NavLastIds[ImGuiNavLayer_Menu] = 0;
NavRestoreLayer(new_nav_layer);
}
}
// Window has already passed the IsWindowNavFocusable()
static const char* GetFallbackWindowNameForWindowingList(ImGuiWindow* window)
{
if (window->Flags & ImGuiWindowFlags_Popup)
return "(Popup)";
if ((window->Flags & ImGuiWindowFlags_MenuBar) && strcmp(window->Name, "##MainMenuBar") == 0)
return "(Main menu bar)";
if (window->DockNodeAsHost)
return "(Dock node)";
return "(Untitled)";
}
// Overlay displayed when using CTRL+TAB. Called by EndFrame().
void ImGui::NavUpdateWindowingList()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.NavWindowingTarget != NULL);
if (g.NavWindowingTimer < NAV_WINDOWING_LIST_APPEAR_DELAY)
return;
if (g.NavWindowingList == NULL)
g.NavWindowingList = FindWindowByName("###NavWindowingList");
ImGuiViewportP* viewport = /*g.NavWindow ? g.NavWindow->Viewport :*/ (ImGuiViewportP*)GetMainViewport();
SetNextWindowSizeConstraints(ImVec2(viewport->Size.x * 0.20f, viewport->Size.y * 0.20f), ImVec2(FLT_MAX, FLT_MAX));
SetNextWindowPos(viewport->Pos + viewport->Size * 0.5f, ImGuiCond_Always, ImVec2(0.5f, 0.5f));
PushStyleVar(ImGuiStyleVar_WindowPadding, g.Style.WindowPadding * 2.0f);
Begin("###NavWindowingList", NULL, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoFocusOnAppearing | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoInputs | ImGuiWindowFlags_AlwaysAutoResize | ImGuiWindowFlags_NoSavedSettings);
for (int n = g.WindowsFocusOrder.Size - 1; n >= 0; n--)
{
ImGuiWindow* window = g.WindowsFocusOrder[n];
if (!IsWindowNavFocusable(window))
continue;
const char* label = window->Name;
if (label == FindRenderedTextEnd(label))
label = GetFallbackWindowNameForWindowingList(window);
Selectable(label, g.NavWindowingTarget == window);
}
End();
PopStyleVar();
}
//-----------------------------------------------------------------------------
// [SECTION] COLUMNS
// In the current version, Columns are very weak. Needs to be replaced with a more full-featured system.
//-----------------------------------------------------------------------------
void ImGui::NextColumn()
{
ImGuiWindow* window = GetCurrentWindow();
if (window->SkipItems || window->DC.ColumnsSet == NULL)
return;
ImGuiContext& g = *GImGui;
PopItemWidth();
PopClipRect();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
if (++columns->Current < columns->Count)
{
// Columns 1+ cancel out IndentX
window->DC.ColumnsOffset.x = GetColumnOffset(columns->Current) - window->DC.Indent.x + g.Style.ItemSpacing.x;
window->DrawList->ChannelsSetCurrent(columns->Current);
}
else
{
window->DC.ColumnsOffset.x = 0.0f;
window->DrawList->ChannelsSetCurrent(0);
columns->Current = 0;
columns->LineMinY = columns->LineMaxY;
}
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
window->DC.CursorPos.y = columns->LineMinY;
window->DC.CurrentLineSize = ImVec2(0.0f, 0.0f);
window->DC.CurrentLineTextBaseOffset = 0.0f;
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f); // FIXME: Move on columns setup
}
int ImGui::GetColumnIndex()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsSet ? window->DC.ColumnsSet->Current : 0;
}
int ImGui::GetColumnsCount()
{
ImGuiWindow* window = GetCurrentWindowRead();
return window->DC.ColumnsSet ? window->DC.ColumnsSet->Count : 1;
}
static float OffsetNormToPixels(const ImGuiColumnsSet* columns, float offset_norm)
{
return offset_norm * (columns->MaxX - columns->MinX);
}
static float PixelsToOffsetNorm(const ImGuiColumnsSet* columns, float offset)
{
return offset / (columns->MaxX - columns->MinX);
}
static inline float GetColumnsRectHalfWidth() { return 4.0f; }
static float GetDraggedColumnOffset(ImGuiColumnsSet* columns, int column_index)
{
// Active (dragged) column always follow mouse. The reason we need this is that dragging a column to the right edge of an auto-resizing
// window creates a feedback loop because we store normalized positions. So while dragging we enforce absolute positioning.
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(column_index > 0); // We are not supposed to drag column 0.
IM_ASSERT(g.ActiveId == columns->ID + ImGuiID(column_index));
float x = g.IO.MousePos.x - g.ActiveIdClickOffset.x + GetColumnsRectHalfWidth() - window->Pos.x;
x = ImMax(x, ImGui::GetColumnOffset(column_index - 1) + g.Style.ColumnsMinSpacing);
if ((columns->Flags & ImGuiColumnsFlags_NoPreserveWidths))
x = ImMin(x, ImGui::GetColumnOffset(column_index + 1) - g.Style.ColumnsMinSpacing);
return x;
}
float ImGui::GetColumnOffset(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const float t = columns->Columns[column_index].OffsetNorm;
const float x_offset = ImLerp(columns->MinX, columns->MaxX, t);
return x_offset;
}
static float GetColumnWidthEx(ImGuiColumnsSet* columns, int column_index, bool before_resize = false)
{
if (column_index < 0)
column_index = columns->Current;
float offset_norm;
if (before_resize)
offset_norm = columns->Columns[column_index + 1].OffsetNormBeforeResize - columns->Columns[column_index].OffsetNormBeforeResize;
else
offset_norm = columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm;
return OffsetNormToPixels(columns, offset_norm);
}
float ImGui::GetColumnWidth(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
return OffsetNormToPixels(columns, columns->Columns[column_index + 1].OffsetNorm - columns->Columns[column_index].OffsetNorm);
}
void ImGui::SetColumnOffset(int column_index, float offset)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
IM_ASSERT(column_index < columns->Columns.Size);
const bool preserve_width = !(columns->Flags & ImGuiColumnsFlags_NoPreserveWidths) && (column_index < columns->Count-1);
const float width = preserve_width ? GetColumnWidthEx(columns, column_index, columns->IsBeingResized) : 0.0f;
if (!(columns->Flags & ImGuiColumnsFlags_NoForceWithinWindow))
offset = ImMin(offset, columns->MaxX - g.Style.ColumnsMinSpacing * (columns->Count - column_index));
columns->Columns[column_index].OffsetNorm = PixelsToOffsetNorm(columns, offset - columns->MinX);
if (preserve_width)
SetColumnOffset(column_index + 1, offset + ImMax(g.Style.ColumnsMinSpacing, width));
}
void ImGui::SetColumnWidth(int column_index, float width)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
if (column_index < 0)
column_index = columns->Current;
SetColumnOffset(column_index + 1, GetColumnOffset(column_index) + width);
}
void ImGui::PushColumnClipRect(int column_index)
{
ImGuiWindow* window = GetCurrentWindowRead();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
if (column_index < 0)
column_index = columns->Current;
PushClipRect(columns->Columns[column_index].ClipRect.Min, columns->Columns[column_index].ClipRect.Max, false);
}
static ImGuiColumnsSet* FindOrAddColumnsSet(ImGuiWindow* window, ImGuiID id)
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
if (window->ColumnsStorage[n].ID == id)
return &window->ColumnsStorage[n];
window->ColumnsStorage.push_back(ImGuiColumnsSet());
ImGuiColumnsSet* columns = &window->ColumnsStorage.back();
columns->ID = id;
return columns;
}
void ImGui::BeginColumns(const char* str_id, int columns_count, ImGuiColumnsFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count > 1);
IM_ASSERT(window->DC.ColumnsSet == NULL); // Nested columns are currently not supported
// Differentiate column ID with an arbitrary prefix for cases where users name their columns set the same as another widget.
// In addition, when an identifier isn't explicitly provided we include the number of columns in the hash to make it uniquer.
PushID(0x11223347 + (str_id ? 0 : columns_count));
ImGuiID id = window->GetID(str_id ? str_id : "columns");
PopID();
// Acquire storage for the columns set
ImGuiColumnsSet* columns = FindOrAddColumnsSet(window, id);
IM_ASSERT(columns->ID == id);
columns->Current = 0;
columns->Count = columns_count;
columns->Flags = flags;
window->DC.ColumnsSet = columns;
// Set state for first column
const float content_region_width = (window->SizeContentsExplicit.x != 0.0f) ? (window->SizeContentsExplicit.x) : (window->InnerClipRect.Max.x - window->Pos.x);
columns->MinX = window->DC.Indent.x - g.Style.ItemSpacing.x; // Lock our horizontal range
columns->MaxX = ImMax(content_region_width - window->Scroll.x, columns->MinX + 1.0f);
columns->StartPosY = window->DC.CursorPos.y;
columns->StartMaxPosX = window->DC.CursorMaxPos.x;
columns->LineMinY = columns->LineMaxY = window->DC.CursorPos.y;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
// Clear data if columns count changed
if (columns->Columns.Size != 0 && columns->Columns.Size != columns_count + 1)
columns->Columns.resize(0);
// Initialize defaults
columns->IsFirstFrame = (columns->Columns.Size == 0);
if (columns->Columns.Size == 0)
{
columns->Columns.reserve(columns_count + 1);
for (int n = 0; n < columns_count + 1; n++)
{
ImGuiColumnData column;
column.OffsetNorm = n / (float)columns_count;
columns->Columns.push_back(column);
}
}
for (int n = 0; n < columns_count; n++)
{
// Compute clipping rectangle
ImGuiColumnData* column = &columns->Columns[n];
float clip_x1 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n) - 1.0f);
float clip_x2 = ImFloor(0.5f + window->Pos.x + GetColumnOffset(n + 1) - 1.0f);
column->ClipRect = ImRect(clip_x1, -FLT_MAX, clip_x2, +FLT_MAX);
column->ClipRect.ClipWith(window->ClipRect);
}
window->DrawList->ChannelsSplit(columns->Count);
PushColumnClipRect();
PushItemWidth(GetColumnWidth() * 0.65f);
}
void ImGui::EndColumns()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = GetCurrentWindow();
ImGuiColumnsSet* columns = window->DC.ColumnsSet;
IM_ASSERT(columns != NULL);
PopItemWidth();
PopClipRect();
window->DrawList->ChannelsMerge();
columns->LineMaxY = ImMax(columns->LineMaxY, window->DC.CursorPos.y);
window->DC.CursorPos.y = columns->LineMaxY;
if (!(columns->Flags & ImGuiColumnsFlags_GrowParentContentsSize))
window->DC.CursorMaxPos.x = columns->StartMaxPosX; // Restore cursor max pos, as columns don't grow parent
// Draw columns borders and handle resize
bool is_being_resized = false;
if (!(columns->Flags & ImGuiColumnsFlags_NoBorder) && !window->SkipItems)
{
const float y1 = columns->StartPosY;
const float y2 = window->DC.CursorPos.y;
int dragging_column = -1;
for (int n = 1; n < columns->Count; n++)
{
float x = window->Pos.x + GetColumnOffset(n);
const ImGuiID column_id = columns->ID + ImGuiID(n);
const float column_hw = GetColumnsRectHalfWidth(); // Half-width for interaction
const ImRect column_rect(ImVec2(x - column_hw, y1), ImVec2(x + column_hw, y2));
KeepAliveID(column_id);
if (IsClippedEx(column_rect, column_id, false))
continue;
bool hovered = false, held = false;
if (!(columns->Flags & ImGuiColumnsFlags_NoResize))
{
ButtonBehavior(column_rect, column_id, &hovered, &held);
if (hovered || held)
g.MouseCursor = ImGuiMouseCursor_ResizeEW;
if (held && !(columns->Columns[n].Flags & ImGuiColumnsFlags_NoResize))
dragging_column = n;
}
// Draw column (we clip the Y boundaries CPU side because very long triangles are mishandled by some GPU drivers.)
const ImU32 col = GetColorU32(held ? ImGuiCol_SeparatorActive : hovered ? ImGuiCol_SeparatorHovered : ImGuiCol_Separator);
const float xi = (float)(int)x;
window->DrawList->AddLine(ImVec2(xi, ImMax(y1 + 1.0f, window->ClipRect.Min.y)), ImVec2(xi, ImMin(y2, window->ClipRect.Max.y)), col);
}
// Apply dragging after drawing the column lines, so our rendered lines are in sync with how items were displayed during the frame.
if (dragging_column != -1)
{
if (!columns->IsBeingResized)
for (int n = 0; n < columns->Count + 1; n++)
columns->Columns[n].OffsetNormBeforeResize = columns->Columns[n].OffsetNorm;
columns->IsBeingResized = is_being_resized = true;
float x = GetDraggedColumnOffset(columns, dragging_column);
SetColumnOffset(dragging_column, x);
}
}
columns->IsBeingResized = is_being_resized;
window->DC.ColumnsSet = NULL;
window->DC.ColumnsOffset.x = 0.0f;
window->DC.CursorPos.x = (float)(int)(window->Pos.x + window->DC.Indent.x + window->DC.ColumnsOffset.x);
}
// [2018-03: This is currently the only public API, while we are working on making BeginColumns/EndColumns user-facing]
void ImGui::Columns(int columns_count, const char* id, bool border)
{
ImGuiWindow* window = GetCurrentWindow();
IM_ASSERT(columns_count >= 1);
ImGuiColumnsFlags flags = (border ? 0 : ImGuiColumnsFlags_NoBorder);
//flags |= ImGuiColumnsFlags_NoPreserveWidths; // NB: Legacy behavior
if (window->DC.ColumnsSet != NULL && window->DC.ColumnsSet->Count == columns_count && window->DC.ColumnsSet->Flags == flags)
return;
if (window->DC.ColumnsSet != NULL)
EndColumns();
if (columns_count != 1)
BeginColumns(id, columns_count, flags);
}
//-----------------------------------------------------------------------------
// [SECTION] DRAG AND DROP
//-----------------------------------------------------------------------------
void ImGui::ClearDragDrop()
{
ImGuiContext& g = *GImGui;
g.DragDropActive = false;
g.DragDropPayload.Clear();
g.DragDropAcceptFlags = ImGuiDragDropFlags_None;
g.DragDropAcceptIdCurr = g.DragDropAcceptIdPrev = 0;
g.DragDropAcceptIdCurrRectSurface = FLT_MAX;
g.DragDropAcceptFrameCount = -1;
g.DragDropPayloadBufHeap.clear();
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
}
// Call when current ID is active.
// When this returns true you need to: a) call SetDragDropPayload() exactly once, b) you may render the payload visual/description, c) call EndDragDropSource()
bool ImGui::BeginDragDropSource(ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
bool source_drag_active = false;
ImGuiID source_id = 0;
ImGuiID source_parent_id = 0;
int mouse_button = 0;
if (!(flags & ImGuiDragDropFlags_SourceExtern))
{
source_id = window->DC.LastItemId;
if (source_id != 0 && g.ActiveId != source_id) // Early out for most common case
return false;
if (g.IO.MouseDown[mouse_button] == false)
return false;
if (source_id == 0)
{
// If you want to use BeginDragDropSource() on an item with no unique identifier for interaction, such as Text() or Image(), you need to:
// A) Read the explanation below, B) Use the ImGuiDragDropFlags_SourceAllowNullID flag, C) Swallow your programmer pride.
if (!(flags & ImGuiDragDropFlags_SourceAllowNullID))
{
IM_ASSERT(0);
return false;
}
// Magic fallback (=somehow reprehensible) to handle items with no assigned ID, e.g. Text(), Image()
// We build a throwaway ID based on current ID stack + relative AABB of items in window.
// THE IDENTIFIER WON'T SURVIVE ANY REPOSITIONING OF THE WIDGET, so if your widget moves your dragging operation will be canceled.
// We don't need to maintain/call ClearActiveID() as releasing the button will early out this function and trigger !ActiveIdIsAlive.
bool is_hovered = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect) != 0;
if (!is_hovered && (g.ActiveId == 0 || g.ActiveIdWindow != window))
return false;
source_id = window->DC.LastItemId = window->GetIDFromRectangle(window->DC.LastItemRect);
if (is_hovered)
SetHoveredID(source_id);
if (is_hovered && g.IO.MouseClicked[mouse_button])
{
SetActiveID(source_id, window);
FocusWindow(window);
}
if (g.ActiveId == source_id) // Allow the underlying widget to display/return hovered during the mouse release frame, else we would get a flicker.
g.ActiveIdAllowOverlap = is_hovered;
}
else
{
g.ActiveIdAllowOverlap = false;
}
if (g.ActiveId != source_id)
return false;
source_parent_id = window->IDStack.back();
source_drag_active = IsMouseDragging(mouse_button);
}
else
{
window = NULL;
source_id = ImHashStr("#SourceExtern", 0);
source_drag_active = true;
}
if (source_drag_active)
{
if (!g.DragDropActive)
{
IM_ASSERT(source_id != 0);
ClearDragDrop();
ImGuiPayload& payload = g.DragDropPayload;
payload.SourceId = source_id;
payload.SourceParentId = source_parent_id;
g.DragDropActive = true;
g.DragDropSourceFlags = flags;
g.DragDropMouseButton = mouse_button;
}
g.DragDropSourceFrameCount = g.FrameCount;
g.DragDropWithinSourceOrTarget = true;
if (!(flags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
{
// Target can request the Source to not display its tooltip (we use a dedicated flag to make this request explicit)
// We unfortunately can't just modify the source flags and skip the call to BeginTooltip, as caller may be emitting contents.
BeginTooltip();
if (g.DragDropAcceptIdPrev && (g.DragDropAcceptFlags & ImGuiDragDropFlags_AcceptNoPreviewTooltip))
{
ImGuiWindow* tooltip_window = g.CurrentWindow;
tooltip_window->SkipItems = true;
tooltip_window->HiddenFramesRegular = 1;
}
}
if (!(flags & ImGuiDragDropFlags_SourceNoDisableHover) && !(flags & ImGuiDragDropFlags_SourceExtern))
window->DC.LastItemStatusFlags &= ~ImGuiItemStatusFlags_HoveredRect;
return true;
}
return false;
}
void ImGui::EndDragDropSource()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget && "Not after a BeginDragDropSource()?");
if (!(g.DragDropSourceFlags & ImGuiDragDropFlags_SourceNoPreviewTooltip))
EndTooltip();
// Discard the drag if have not called SetDragDropPayload()
if (g.DragDropPayload.DataFrameCount == -1)
ClearDragDrop();
g.DragDropWithinSourceOrTarget = false;
}
// Use 'cond' to choose to submit payload on drag start or every frame
bool ImGui::SetDragDropPayload(const char* type, const void* data, size_t data_size, ImGuiCond cond)
{
ImGuiContext& g = *GImGui;
ImGuiPayload& payload = g.DragDropPayload;
if (cond == 0)
cond = ImGuiCond_Always;
IM_ASSERT(type != NULL);
IM_ASSERT(strlen(type) < IM_ARRAYSIZE(payload.DataType) && "Payload type can be at most 32 characters long");
IM_ASSERT((data != NULL && data_size > 0) || (data == NULL && data_size == 0));
IM_ASSERT(cond == ImGuiCond_Always || cond == ImGuiCond_Once);
IM_ASSERT(payload.SourceId != 0); // Not called between BeginDragDropSource() and EndDragDropSource()
if (cond == ImGuiCond_Always || payload.DataFrameCount == -1)
{
// Copy payload
ImStrncpy(payload.DataType, type, IM_ARRAYSIZE(payload.DataType));
g.DragDropPayloadBufHeap.resize(0);
if (data_size > sizeof(g.DragDropPayloadBufLocal))
{
// Store in heap
g.DragDropPayloadBufHeap.resize((int)data_size);
payload.Data = g.DragDropPayloadBufHeap.Data;
memcpy(payload.Data, data, data_size);
}
else if (data_size > 0)
{
// Store locally
memset(&g.DragDropPayloadBufLocal, 0, sizeof(g.DragDropPayloadBufLocal));
payload.Data = g.DragDropPayloadBufLocal;
memcpy(payload.Data, data, data_size);
}
else
{
payload.Data = NULL;
}
payload.DataSize = (int)data_size;
}
payload.DataFrameCount = g.FrameCount;
return (g.DragDropAcceptFrameCount == g.FrameCount) || (g.DragDropAcceptFrameCount == g.FrameCount - 1);
}
bool ImGui::BeginDragDropTargetCustom(const ImRect& bb, ImGuiID id)
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
return false;
IM_ASSERT(id != 0);
if (!IsMouseHoveringRect(bb.Min, bb.Max) || (id == g.DragDropPayload.SourceId))
return false;
if (window->SkipItems)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = bb;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
// We don't use BeginDragDropTargetCustom() and duplicate its code because:
// 1) we use LastItemRectHoveredRect which handles items that pushes a temporarily clip rectangle in their code. Calling BeginDragDropTargetCustom(LastItemRect) would not handle them.
// 2) and it's faster. as this code may be very frequently called, we want to early out as fast as we can.
// Also note how the HoveredWindow test is positioned differently in both functions (in both functions we optimize for the cheapest early out case)
bool ImGui::BeginDragDropTarget()
{
ImGuiContext& g = *GImGui;
if (!g.DragDropActive)
return false;
ImGuiWindow* window = g.CurrentWindow;
if (!(window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HoveredRect))
return false;
if (g.HoveredWindowUnderMovingWindow == NULL || window->RootWindow != g.HoveredWindowUnderMovingWindow->RootWindow)
return false;
const ImRect& display_rect = (window->DC.LastItemStatusFlags & ImGuiItemStatusFlags_HasDisplayRect) ? window->DC.LastItemDisplayRect : window->DC.LastItemRect;
ImGuiID id = window->DC.LastItemId;
if (id == 0)
id = window->GetIDFromRectangle(display_rect);
if (g.DragDropPayload.SourceId == id)
return false;
IM_ASSERT(g.DragDropWithinSourceOrTarget == false);
g.DragDropTargetRect = display_rect;
g.DragDropTargetId = id;
g.DragDropWithinSourceOrTarget = true;
return true;
}
bool ImGui::IsDragDropPayloadBeingAccepted()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive && g.DragDropAcceptIdPrev != 0;
}
const ImGuiPayload* ImGui::AcceptDragDropPayload(const char* type, ImGuiDragDropFlags flags)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImGuiPayload& payload = g.DragDropPayload;
IM_ASSERT(g.DragDropActive); // Not called between BeginDragDropTarget() and EndDragDropTarget() ?
IM_ASSERT(payload.DataFrameCount != -1); // Forgot to call EndDragDropTarget() ?
if (type != NULL && !payload.IsDataType(type))
return NULL;
// Accept smallest drag target bounding box, this allows us to nest drag targets conveniently without ordering constraints.
// NB: We currently accept NULL id as target. However, overlapping targets requires a unique ID to function!
const bool was_accepted_previously = (g.DragDropAcceptIdPrev == g.DragDropTargetId);
ImRect r = g.DragDropTargetRect;
float r_surface = r.GetWidth() * r.GetHeight();
if (r_surface < g.DragDropAcceptIdCurrRectSurface)
{
g.DragDropAcceptFlags = flags;
g.DragDropAcceptIdCurr = g.DragDropTargetId;
g.DragDropAcceptIdCurrRectSurface = r_surface;
}
// Render default drop visuals
payload.Preview = was_accepted_previously;
flags |= (g.DragDropSourceFlags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect); // Source can also inhibit the preview (useful for external sources that lives for 1 frame)
if (!(flags & ImGuiDragDropFlags_AcceptNoDrawDefaultRect) && payload.Preview)
{
// FIXME-DRAG: Settle on a proper default visuals for drop target.
r.Expand(3.5f);
bool push_clip_rect = !window->ClipRect.Contains(r);
if (push_clip_rect) window->DrawList->PushClipRect(r.Min-ImVec2(1,1), r.Max+ImVec2(1,1));
window->DrawList->AddRect(r.Min, r.Max, GetColorU32(ImGuiCol_DragDropTarget), 0.0f, ~0, 2.0f);
if (push_clip_rect) window->DrawList->PopClipRect();
}
g.DragDropAcceptFrameCount = g.FrameCount;
payload.Delivery = was_accepted_previously && !IsMouseDown(g.DragDropMouseButton); // For extern drag sources affecting os window focus, it's easier to just test !IsMouseDown() instead of IsMouseReleased()
if (!payload.Delivery && !(flags & ImGuiDragDropFlags_AcceptBeforeDelivery))
return NULL;
return &payload;
}
const ImGuiPayload* ImGui::GetDragDropPayload()
{
ImGuiContext& g = *GImGui;
return g.DragDropActive ? &g.DragDropPayload : NULL;
}
// We don't really use/need this now, but added it for the sake of consistency and because we might need it later.
void ImGui::EndDragDropTarget()
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.DragDropActive);
IM_ASSERT(g.DragDropWithinSourceOrTarget);
g.DragDropWithinSourceOrTarget = false;
}
//-----------------------------------------------------------------------------
// [SECTION] DOCKING
//-----------------------------------------------------------------------------
// Docking: Internal Types
// Docking: Forward Declarations
// Docking: ImGuiDockContext
// Docking: ImGuiDockContext Docking/Undocking functions
// Docking: ImGuiDockNode
// Docking: ImGuiDockNode Tree manipulation functions
// Docking: Public Functions (SetWindowDock, DockSpace)
// Docking: Builder Functions
// Docking: Begin/End Functions (called from Begin/End)
// Docking: Settings
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Docking: Internal Types
//-----------------------------------------------------------------------------
static float IMGUI_DOCK_SPLITTER_SIZE = 2.0f;
enum ImGuiDockRequestType
{
ImGuiDockRequestType_None = 0,
ImGuiDockRequestType_Dock,
ImGuiDockRequestType_Undock,
ImGuiDockRequestType_Split // Split is the same as Dock but without a DockPayload
};
struct ImGuiDockRequest
{
ImGuiDockRequestType Type;
ImGuiWindow* DockTargetWindow; // Destination/Target Window to dock into (may be a loose window or a DockNode, might be NULL in which case DockTargetNode cannot be NULL)
ImGuiDockNode* DockTargetNode; // Destination/Target Node to dock into
ImGuiWindow* DockPayload; // Source/Payload window to dock (may be a loose window or a DockNode), [Optional]
ImGuiDir DockSplitDir;
float DockSplitRatio;
bool DockSplitOuter;
ImGuiWindow* UndockTargetWindow;
ImGuiDockNode* UndockTargetNode;
ImGuiDockRequest()
{
Type = ImGuiDockRequestType_None;
DockTargetWindow = DockPayload = UndockTargetWindow = NULL;
DockTargetNode = UndockTargetNode = NULL;
DockSplitDir = ImGuiDir_None;
DockSplitRatio = 0.5f;
DockSplitOuter = false;
}
};
struct ImGuiDockPreviewData
{
ImGuiDockNode FutureNode;
bool IsDropAllowed;
bool IsCenterAvailable;
bool IsSidesAvailable; // Hold your breath, grammar freaks..
bool IsSplitDirExplicit; // Set when hovered the drop rect (vs. implicit SplitDir==None when hovered the window)
ImGuiDockNode* SplitNode;
ImGuiDir SplitDir;
float SplitRatio;
ImRect DropRectsDraw[ImGuiDir_COUNT + 1]; // May be slightly different from hit-testing drop rects used in DockNodeCalcDropRects()
ImGuiDockPreviewData() : FutureNode(0) { IsDropAllowed = IsCenterAvailable = IsSidesAvailable = IsSplitDirExplicit = false; SplitNode = NULL; SplitDir = ImGuiDir_None; SplitRatio = 0.f; }
};
// Persistent Settings data, stored contiguously in SettingsNodes (sizeof() ~32 bytes)
struct ImGuiDockNodeSettings
{
ImGuiID ID;
ImGuiID ParentID;
ImGuiID SelectedTabID;
char SplitAxis;
char Depth;
char IsDockSpace;
char IsCentralNode;
char IsHiddenTabBar;
ImVec2ih Pos;
ImVec2ih Size;
ImVec2ih SizeRef;
ImGuiDockNodeSettings() { ID = ParentID = SelectedTabID = 0; SplitAxis = ImGuiAxis_None; Depth = 0; IsDockSpace = IsCentralNode = IsHiddenTabBar = 0; }
};
struct ImGuiDockContext
{
ImGuiStorage Nodes; // Map ID -> ImGuiDockNode*: Active nodes
ImVector<ImGuiDockRequest> Requests;
ImVector<ImGuiDockNodeSettings> SettingsNodes;
bool WantFullRebuild;
ImGuiDockContext() { WantFullRebuild = false; }
};
//-----------------------------------------------------------------------------
// Docking: Forward Declarations
//-----------------------------------------------------------------------------
namespace ImGui
{
// ImGuiDockContext
static ImGuiDockNode* DockContextAddNode(ImGuiContext* ctx, ImGuiID id);
static ImGuiID DockContextGenNodeID(ImGuiContext* ctx);
static void DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node);
static void DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer);
static void DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node);
static void DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req);
static void DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref = true);
static void DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node);
static void DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx);
static ImGuiDockNode* DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id);
static void DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_refs); // Use root_id==0 to clear all
static void DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count);
static void DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id); // Use root_id==0 to add all
// ImGuiDockNode
static void DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar);
static void DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
static void DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node);
static void DockNodeApplyPosSizeToWindows(ImGuiDockNode* node);
static void DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id);
static void DockNodeHideHostWindow(ImGuiDockNode* node);
static void DockNodeUpdate(ImGuiDockNode* node);
static void DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node);
static void DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window);
static ImGuiID DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar);
static void DockNodeUpdateVisibleFlag(ImGuiDockNode* node);
static void DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window);
static bool DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* payload_window);
static bool DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, ImGuiDockPreviewData* preview_data, bool is_explicit_target, bool is_outer_docking);
static void DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* payload_window, const ImGuiDockPreviewData* preview_data);
static ImRect DockNodeCalcTabBarRect(const ImGuiDockNode* node);
static void DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired);
static bool DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& out_draw, bool outer_docking);
static const char* DockNodeGetHostWindowTitle(ImGuiDockNode* node, char* buf, int buf_size) { ImFormatString(buf, buf_size, "##DockNode_%02X", node->ID); return buf; }
static int DockNodeGetDepth(const ImGuiDockNode* node) { int depth = 0; while (node->ParentNode) { node = node->ParentNode; depth++; } return depth; }
static int DockNodeGetTabOrder(ImGuiWindow* window);
// ImGuiDockNode tree manipulations
static void DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_first_child, float split_ratio, ImGuiDockNode* new_node);
static void DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child);
static void DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size);
static void DockNodeTreeUpdateSplitter(ImGuiDockNode* node);
static ImGuiDockNode* DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos);
static ImGuiDockNode* DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node);
// Settings
static void DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id);
static void DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count);
static ImGuiDockNodeSettings* DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID node_id);
static void* DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name);
static void DockSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line);
static void DockSettingsHandler_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf);
}
//-----------------------------------------------------------------------------
// Docking: ImGuiDockContext
//-----------------------------------------------------------------------------
// The lifetime model is different from the one of regular windows: we always create a ImGuiDockNode for each ImGuiDockNodeSettings,
// or we always hold the entire docking node tree. Nodes are frequently hidden, e.g. if the window(s) or child nodes they host are not active.
// At boot time only, we run a simple GC to remove nodes that have no references.
// Because dock node settings (which are small, contiguous structures) are always mirrored by their corresponding dock nodes (more complete structures),
// we can also very easily recreate the nodes from scratch given the settings data (this is what DockContextRebuild() does).
// This is convenient as docking reconfiguration can be implemented by mostly poking at the simpler settings data.
//-----------------------------------------------------------------------------
void ImGui::DockContextInitialize(ImGuiContext* ctx)
{
ImGuiContext& g = *ctx;
IM_ASSERT(g.DockContext == NULL);
g.DockContext = IM_NEW(ImGuiDockContext)();
// Add .ini handle for persistent docking data
ImGuiSettingsHandler ini_handler;
ini_handler.TypeName = "Docking";
ini_handler.TypeHash = ImHashStr("Docking", 0, 0);
ini_handler.ReadOpenFn = DockSettingsHandler_ReadOpen;
ini_handler.ReadLineFn = DockSettingsHandler_ReadLine;
ini_handler.WriteAllFn = DockSettingsHandler_WriteAll;
g.SettingsHandlers.push_back(ini_handler);
}
void ImGui::DockContextShutdown(ImGuiContext* ctx)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
IM_DELETE(node);
IM_DELETE(g.DockContext);
g.DockContext = NULL;
}
void ImGui::DockContextOnLoadSettings(ImGuiContext* ctx)
{
ImGuiDockContext* dc = ctx->DockContext;
DockContextPruneUnusedSettingsNodes(ctx);
DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
}
void ImGui::DockContextClearNodes(ImGuiContext* ctx, ImGuiID root_id, bool clear_persistent_docking_references)
{
IM_ASSERT(ctx == GImGui);
DockBuilderRemoveNodeDockedWindows(root_id, clear_persistent_docking_references);
DockBuilderRemoveNodeChildNodes(root_id);
}
// This function also acts as a defacto test to make sure we can rebuild from scratch without a glitch
void ImGui::DockContextRebuild(ImGuiContext* ctx)
{
//IMGUI_DEBUG_LOG("[docking] full rebuild\n");
ImGuiDockContext* dc = ctx->DockContext;
SaveIniSettingsToMemory();
ImGuiID root_id = 0; // Rebuild all
DockContextClearNodes(ctx, root_id, false);
DockContextBuildNodesFromSettings(ctx, dc->SettingsNodes.Data, dc->SettingsNodes.Size);
DockContextBuildAddWindowsToNodes(ctx, root_id);
}
// Docking context update function, called by NewFrame()
void ImGui::DockContextNewFrameUpdateUndocking(ImGuiContext* ctx)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
{
if (dc->Nodes.Data.Size > 0 || dc->Requests.Size > 0)
DockContextClearNodes(ctx, 0, true);
return;
}
// Setting NoSplit at runtime merges all nodes
if (g.IO.ConfigDockingNoSplit)
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
if (node->IsRootNode() && node->IsSplitNode())
{
DockBuilderRemoveNodeChildNodes(node->ID);
//dc->WantFullRebuild = true;
}
// Process full rebuild
#if 0
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_C)))
dc->WantFullRebuild = true;
#endif
if (dc->WantFullRebuild)
{
DockContextRebuild(ctx);
dc->WantFullRebuild = false;
}
// Process Undocking requests (we need to process them _before_ the UpdateMouseMovingWindowNewFrame call in NewFrame)
for (int n = 0; n < dc->Requests.Size; n++)
{
ImGuiDockRequest* req = &dc->Requests[n];
if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetWindow)
DockContextProcessUndockWindow(ctx, req->UndockTargetWindow);
else if (req->Type == ImGuiDockRequestType_Undock && req->UndockTargetNode)
DockContextProcessUndockNode(ctx, req->UndockTargetNode);
}
}
// Docking context update function, called by NewFrame()
void ImGui::DockContextNewFrameUpdateDocking(ImGuiContext* ctx)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
return;
// Process Docking requests
for (int n = 0; n < dc->Requests.Size; n++)
if (dc->Requests[n].Type == ImGuiDockRequestType_Dock)
DockContextProcessDock(ctx, &dc->Requests[n]);
dc->Requests.resize(0);
// Create windows for each automatic docking nodes
// We can have NULL pointers when we delete nodes, but because ID are recycled this should amortize nicely (and our node count will never be very high)
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
if (node->IsRootNode() && !node->IsDockSpace())
DockNodeUpdate(node);
}
static ImGuiDockNode* ImGui::DockContextFindNodeByID(ImGuiContext* ctx, ImGuiID id)
{
return (ImGuiDockNode*)ctx->DockContext->Nodes.GetVoidPtr(id);
}
static ImGuiID ImGui::DockContextGenNodeID(ImGuiContext* ctx)
{
// Generate an ID for new node (the exact ID value doesn't matter as long as it is not already used)
// FIXME-OPT FIXME-DOCKING: This is suboptimal, even if the node count is small enough not to be a worry. We should poke in ctx->Nodes to find a suitable ID faster.
ImGuiID id = 0x0001;
while (DockContextFindNodeByID(ctx, id) != NULL)
id++;
return id;
}
static ImGuiDockNode* ImGui::DockContextAddNode(ImGuiContext* ctx, ImGuiID id)
{
// Generate an ID for the new node (the exact ID value doesn't matter as long as it is not already used) and add the first window.
if (id == 0)
id = DockContextGenNodeID(ctx);
else
IM_ASSERT(DockContextFindNodeByID(ctx, id) == NULL);
ImGuiDockNode* node = IM_NEW(ImGuiDockNode)(id);
ctx->DockContext->Nodes.SetVoidPtr(node->ID, node);
return node;
}
static void ImGui::DockContextRemoveNode(ImGuiContext* ctx, ImGuiDockNode* node, bool merge_sibling_into_parent_node)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
//printf("[%05d] RemoveNode 0x%04X\n", node->ID);
IM_ASSERT(DockContextFindNodeByID(ctx, node->ID) == node);
IM_ASSERT(node->ChildNodes[0] == NULL && node->ChildNodes[1] == NULL);
IM_ASSERT(node->Windows.Size == 0);
if (node->HostWindow)
node->HostWindow->DockNodeAsHost = NULL;
ImGuiDockNode* parent_node = node->ParentNode;
const bool merge = (merge_sibling_into_parent_node && parent_node != NULL);
if (merge)
{
IM_ASSERT(parent_node->ChildNodes[0] == node || parent_node->ChildNodes[1] == node);
ImGuiDockNode* sibling_node = (parent_node->ChildNodes[0] == node ? parent_node->ChildNodes[1] : parent_node->ChildNodes[0]);
DockNodeTreeMerge(&g, parent_node, sibling_node);
}
else
{
for (int n = 0; parent_node && n < IM_ARRAYSIZE(parent_node->ChildNodes); n++)
if (parent_node->ChildNodes[n] == node)
node->ParentNode->ChildNodes[n] = NULL;
dc->Nodes.SetVoidPtr(node->ID, NULL);
IM_DELETE(node);
}
}
static int IMGUI_CDECL DockNodeComparerDepthMostFirst(const void* lhs, const void* rhs)
{
const ImGuiDockNode* a = *(const ImGuiDockNode* const*)lhs;
const ImGuiDockNode* b = *(const ImGuiDockNode* const*)rhs;
return ImGui::DockNodeGetDepth(b) - ImGui::DockNodeGetDepth(a);
}
// Pre C++0x doesn't allow us to use a function-local type (without linkage) as template parameter, so we moved this here.
struct ImGuiDockContextPruneNodeData
{
int CountWindows, CountChildWindows, CountChildNodes;
ImGuiID RootID;
ImGuiDockContextPruneNodeData() { CountWindows = CountChildWindows = CountChildNodes = 0; RootID = 0; }
};
// Garbage collect unused nodes (run once at init time)
static void ImGui::DockContextPruneUnusedSettingsNodes(ImGuiContext* ctx)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
IM_ASSERT(g.Windows.Size == 0);
ImPool<ImGuiDockContextPruneNodeData> pool;
pool.Reserve(dc->SettingsNodes.Size);
// Count child nodes and compute RootID
for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
{
ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
ImGuiDockContextPruneNodeData* parent_data = settings->ParentID ? pool.GetByKey(settings->ParentID) : 0;
pool.GetOrAddByKey(settings->ID)->RootID = parent_data ? parent_data->RootID : settings->ID;
if (settings->ParentID)
pool.GetOrAddByKey(settings->ParentID)->CountChildNodes++;
}
// Count reference to dock ids from window settings
for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++)
if (ImGuiID dock_id = g.SettingsWindows[settings_n].DockId)
if (ImGuiDockContextPruneNodeData* data = pool.GetByKey(dock_id))
{
ImGuiDockContextPruneNodeData* data_root = (data->RootID == dock_id) ? data : pool.GetByKey(data->RootID);
data->CountWindows++;
data_root->CountChildWindows++;
}
// Prune
for (int settings_n = 0; settings_n < dc->SettingsNodes.Size; settings_n++)
{
ImGuiDockNodeSettings* settings = &dc->SettingsNodes[settings_n];
ImGuiDockContextPruneNodeData* data = pool.GetByKey(settings->ID);
if (data->CountWindows > 1)
continue;
ImGuiDockContextPruneNodeData* data_root = (data->RootID == settings->ID) ? data : pool.GetByKey(data->RootID);
bool remove = false;
remove |= (data->CountWindows == 1 && settings->ParentID == 0 && data->CountChildNodes == 0 && !settings->IsCentralNode); // Floating root node with only 1 window
remove |= (data->CountWindows == 0 && settings->ParentID == 0 && data->CountChildNodes == 0); // Leaf nodes with 0 window
remove |= (data_root->CountChildWindows == 0);
if (remove)
{
DockSettingsRemoveNodeReferences(&settings->ID, 1);
settings->ID = 0;
}
}
}
static void ImGui::DockContextBuildNodesFromSettings(ImGuiContext* ctx, ImGuiDockNodeSettings* node_settings_array, int node_settings_count)
{
// Build nodes
for (int node_n = 0; node_n < node_settings_count; node_n++)
{
ImGuiDockNodeSettings* settings = &node_settings_array[node_n];
if (settings->ID == 0)
continue;
ImGuiDockNode* node = DockContextAddNode(ctx, settings->ID);
node->ParentNode = settings->ParentID ? DockContextFindNodeByID(ctx, settings->ParentID) : NULL;
node->Pos = ImVec2(settings->Pos.x, settings->Pos.y);
node->Size = ImVec2(settings->Size.x, settings->Size.y);
node->SizeRef = ImVec2(settings->SizeRef.x, settings->SizeRef.y);
if (node->ParentNode && node->ParentNode->ChildNodes[0] == NULL)
node->ParentNode->ChildNodes[0] = node;
else if (node->ParentNode && node->ParentNode->ChildNodes[1] == NULL)
node->ParentNode->ChildNodes[1] = node;
node->SelectedTabID = settings->SelectedTabID;
node->SplitAxis = settings->SplitAxis;
if (settings->IsDockSpace)
node->Flags |= ImGuiDockNodeFlags_Dockspace;
node->IsCentralNode = settings->IsCentralNode != 0;
node->IsHiddenTabBar = settings->IsHiddenTabBar != 0;
// Bind host window immediately if it already exist (in case of a rebuild)
// This is useful as the RootWindowForTitleBarHighlight links necessary to highlight the currently focused node requires node->HostWindow to be set.
char host_window_title[20];
ImGuiDockNode* root_node = DockNodeGetRootNode(node);
node->HostWindow = FindWindowByName(DockNodeGetHostWindowTitle(root_node, host_window_title, IM_ARRAYSIZE(host_window_title)));
}
}
void ImGui::DockContextBuildAddWindowsToNodes(ImGuiContext* ctx, ImGuiID root_id)
{
// Rebind all windows to nodes (they can also lazily rebind but we'll have a visible glitch during the first frame)
ImGuiContext& g = *ctx;
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (window->DockId == 0 || window->LastFrameActive < g.FrameCount - 1)
continue;
if (window->DockNode != NULL)
continue;
ImGuiDockNode* node = DockContextFindNodeByID(ctx, window->DockId);
IM_ASSERT(node != NULL); // This should have been called after DockContextBuildNodesFromSettings()
if (root_id == 0 || DockNodeGetRootNode(node)->ID == root_id)
DockNodeAddWindow(node, window, true);
}
}
//-----------------------------------------------------------------------------
// Docking: ImGuiDockContext Docking/Undocking functions
//-----------------------------------------------------------------------------
void ImGui::DockContextQueueDock(ImGuiContext* ctx, ImGuiWindow* target, ImGuiDockNode* target_node, ImGuiWindow* payload, ImGuiDir split_dir, float split_ratio, bool split_outer)
{
IM_ASSERT(target != payload);
ImGuiDockRequest req;
req.Type = ImGuiDockRequestType_Dock;
req.DockTargetWindow = target;
req.DockTargetNode = target_node;
req.DockPayload = payload;
req.DockSplitDir = split_dir;
req.DockSplitRatio = split_ratio;
req.DockSplitOuter = split_outer;
ctx->DockContext->Requests.push_back(req);
}
void ImGui::DockContextQueueUndockWindow(ImGuiContext* ctx, ImGuiWindow* window)
{
ImGuiDockRequest req;
req.Type = ImGuiDockRequestType_Undock;
req.UndockTargetWindow = window;
ctx->DockContext->Requests.push_back(req);
}
void ImGui::DockContextQueueUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
{
ImGuiDockRequest req;
req.Type = ImGuiDockRequestType_Undock;
req.UndockTargetNode = node;
ctx->DockContext->Requests.push_back(req);
}
void ImGui::DockContextQueueNotifyRemovedNode(ImGuiContext* ctx, ImGuiDockNode* node)
{
ImGuiDockContext* dc = ctx->DockContext;
for (int n = 0; n < dc->Requests.Size; n++)
if (dc->Requests[n].DockTargetNode == node)
dc->Requests[n].Type = ImGuiDockRequestType_None;
}
void ImGui::DockContextProcessDock(ImGuiContext* ctx, ImGuiDockRequest* req)
{
IM_ASSERT((req->Type == ImGuiDockRequestType_Dock && req->DockPayload != NULL) || (req->Type == ImGuiDockRequestType_Split && req->DockPayload == NULL));
IM_ASSERT(req->DockTargetWindow != NULL || req->DockTargetNode != NULL);
ImGuiContext& g = *ctx;
ImGuiWindow* payload_window = req->DockPayload; // Optional
ImGuiWindow* target_window = req->DockTargetWindow;
ImGuiDockNode* target_node = req->DockTargetNode;
// Decide which Tab will be selected at the end of the operation
ImGuiID next_selected_id = 0;
ImGuiDockNode* payload_node = NULL;
if (payload_window)
{
payload_node = payload_window->DockNodeAsHost;
payload_window->DockNodeAsHost = NULL; // Important to clear this as the node will have its life as a child which might be merged/deleted later.
if (payload_node && payload_node->IsLeafNode())
next_selected_id = payload_node->TabBar->NextSelectedTabId ? payload_node->TabBar->NextSelectedTabId : payload_node->TabBar->SelectedTabId;
if (payload_node == NULL)
next_selected_id = payload_window->ID;
}
// FIXME-DOCK: When we are trying to dock an existing single-window node into a loose window, transfer Node ID as well
if (target_node)
IM_ASSERT(target_node->LastFrameAlive < g.FrameCount);
if (target_node && target_window && target_node == target_window->DockNodeAsHost)
IM_ASSERT(target_node->Windows.Size > 0 || target_node->IsSplitNode() || target_node->IsCentralNode);
// Create new node and add existing window to it
if (target_node == NULL)
{
target_node = DockContextAddNode(ctx, 0);
target_node->Pos = target_window->Pos;
target_node->Size = target_window->Size;
if (target_window->DockNodeAsHost == NULL)
{
DockNodeAddWindow(target_node, target_window, true);
target_node->TabBar->Tabs[0].Flags &= ~ImGuiTabItemFlags_Unsorted;
target_window->DockIsActive = true;
}
}
ImGuiDir split_dir = req->DockSplitDir;
if (split_dir != ImGuiDir_None)
{
// Split into one, one side will be our payload node unless we are dropping a loose window
const ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
const int split_inheritor_child_idx = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0; // Current contents will be moved to the opposite side
const float split_ratio = req->DockSplitRatio;
DockNodeTreeSplit(ctx, target_node, split_axis, split_inheritor_child_idx, split_ratio, payload_node); // payload_node may be NULL here!
ImGuiDockNode* new_node = target_node->ChildNodes[split_inheritor_child_idx ^ 1];
new_node->HostWindow = target_node->HostWindow;
target_node = new_node;
}
target_node->IsHiddenTabBar = false;
if (target_node != payload_node)
{
// Create tab bar before we call DockNodeMoveWindows (which would attempt to move the old tab-bar, which would lead us to payload tabs wrongly appearing before target tabs!)
if (target_node->Windows.Size > 0 && target_node->TabBar == NULL)
{
target_node->TabBar = IM_NEW(ImGuiTabBar)();
for (int n = 0; n < target_node->Windows.Size; n++)
TabBarAddTab(target_node->TabBar, ImGuiTabItemFlags_None, target_node->Windows[n]);
}
if (payload_node != NULL)
{
// Transfer full payload node (with 1+ child windows or child nodes)
if (payload_node->IsSplitNode())
{
if (target_node->Windows.Size > 0)
{
// We can dock into a node that already has windows _only_ if our payload is a node tree with a single visible node.
// In this situation, we move the windows of the target node into the currently visible node of the payload.
// This allows us to preserve some of the underlying dock tree settings nicely.
IM_ASSERT(payload_node->OnlyNodeWithWindows != NULL); // The docking should have been blocked by DockNodePreviewDockCalc() early on and never submitted.
ImGuiDockNode* visible_node = payload_node->OnlyNodeWithWindows;
if (visible_node->TabBar)
IM_ASSERT(visible_node->TabBar->Tabs.Size > 0);
DockNodeMoveWindows(target_node, visible_node);
DockNodeMoveWindows(visible_node, target_node);
DockSettingsRenameNodeReferences(target_node->ID, visible_node->ID);
}
if (target_node->IsCentralNode)
{
// Central node property needs to be moved to a leaf node, pick the last focused one.
ImGuiDockNode* last_focused_node = DockContextFindNodeByID(ctx, payload_node->LastFocusedNodeID);
IM_ASSERT(last_focused_node != NULL && DockNodeGetRootNode(last_focused_node) == DockNodeGetRootNode(payload_node));
last_focused_node->IsCentralNode = true;
target_node->IsCentralNode = false;
}
IM_ASSERT(target_node->Windows.Size == 0);
DockNodeMoveChildNodes(target_node, payload_node);
}
else
{
const ImGuiID payload_dock_id = payload_node->ID;
DockNodeMoveWindows(target_node, payload_node);
DockSettingsRenameNodeReferences(payload_dock_id, target_node->ID);
}
DockContextRemoveNode(ctx, payload_node, true);
}
else if (payload_window)
{
// Transfer single window
const ImGuiID payload_dock_id = payload_window->DockId;
target_node->VisibleWindow = payload_window;
DockNodeAddWindow(target_node, payload_window, true);
if (payload_dock_id != 0)
DockSettingsRenameNodeReferences(payload_dock_id, target_node->ID);
}
}
// Update selection immediately
if (ImGuiTabBar* tab_bar = target_node->TabBar)
tab_bar->NextSelectedTabId = next_selected_id;
MarkIniSettingsDirty();
}
void ImGui::DockContextProcessUndockWindow(ImGuiContext* ctx, ImGuiWindow* window, bool clear_persistent_docking_ref)
{
(void)ctx;
if (window->DockNode)
DockNodeRemoveWindow(window->DockNode, window, clear_persistent_docking_ref ? 0 : window->DockId);
else
window->DockId = 0;
window->Collapsed = false;
window->DockIsActive = false;
window->DockTabIsVisible = false;
MarkIniSettingsDirty();
}
void ImGui::DockContextProcessUndockNode(ImGuiContext* ctx, ImGuiDockNode* node)
{
IM_ASSERT(node->IsLeafNode());
IM_ASSERT(node->Windows.Size >= 1);
if (node->IsRootNode() || node->IsCentralNode)
{
// In the case of a root node or central node, the node will have to stay in place. Create a new node to receive the payload.
ImGuiDockNode* new_node = DockContextAddNode(ctx, 0);
DockNodeMoveWindows(new_node, node);
DockSettingsRenameNodeReferences(node->ID, new_node->ID);
for (int n = 0; n < new_node->Windows.Size; n++)
UpdateWindowParentAndRootLinks(new_node->Windows[n], new_node->Windows[n]->Flags, NULL);
new_node->WantMouseMove = true;
}
else
{
// Otherwise delete the previous node by merging the other sibling back into the parent node.
IM_ASSERT(node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
int index_in_parent = (node->ParentNode->ChildNodes[0] == node) ? 0 : 1;
node->ParentNode->ChildNodes[index_in_parent] = NULL;
DockNodeTreeMerge(ctx, node->ParentNode, node->ParentNode->ChildNodes[index_in_parent ^ 1]);
node->ParentNode->AutorityForViewport = ImGuiDataAutority_Window; // The node that stays in place keeps the viewport, so our newly dragged out node will create a new viewport
node->ParentNode = NULL;
node->AutorityForPos = node->AutorityForSize = ImGuiDataAutority_Window;
node->WantMouseMove = true;
}
MarkIniSettingsDirty();
}
//-----------------------------------------------------------------------------
// Docking: ImGuiDockNode
//-----------------------------------------------------------------------------
ImGuiDockNode::ImGuiDockNode(ImGuiID id)
{
ID = id;
Flags = 0;
ParentNode = ChildNodes[0] = ChildNodes[1] = NULL;
TabBar = NULL;
SplitAxis = ImGuiAxis_None;
HostWindow = VisibleWindow = NULL;
CentralNode = OnlyNodeWithWindows = NULL;
LastFrameAlive = LastFrameActive = LastFrameFocused = -1;
LastFocusedNodeID = 0;
SelectedTabID = 0;
WantCloseTabID = 0;
AutorityForPos = AutorityForSize = ImGuiDataAutority_DockNode;
AutorityForViewport = ImGuiDataAutority_Auto;
IsVisible = true;
IsFocused = IsCentralNode = IsHiddenTabBar = HasCloseButton = HasCollapseButton = false;
WantCloseAll = WantLockSizeOnce = WantMouseMove = WantHiddenTabBarUpdate = WantHiddenTabBarToggle = false;
}
ImGuiDockNode::~ImGuiDockNode()
{
IM_DELETE(TabBar);
TabBar = NULL;
ChildNodes[0] = ChildNodes[1] = NULL;
}
int ImGui::DockNodeGetTabOrder(ImGuiWindow* window)
{
ImGuiTabBar* tab_bar = window->DockNode->TabBar;
if (tab_bar == NULL)
return -1;
ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, window->ID);
return tab ? tab_bar->GetTabOrder(tab) : -1;
}
static void ImGui::DockNodeAddWindow(ImGuiDockNode* node, ImGuiWindow* window, bool add_to_tab_bar)
{
ImGuiContext& g = *GImGui; (void)g;
if (window->DockNode)
{
// Can overwrite an existing window->DockNode (e.g. pointing to a disabled DockSpace node)
IM_ASSERT(window->DockNode->ID != node->ID);
DockNodeRemoveWindow(window->DockNode, window, 0);
}
IM_ASSERT(window->DockNode == NULL || window->DockNodeAsHost == NULL);
node->Windows.push_back(window);
node->WantHiddenTabBarUpdate = true;
window->DockNode = node;
window->DockId = node->ID;
window->DockIsActive = (node->Windows.Size > 1);
window->DockTabWantClose = false;
// If 2+ windows appeared on the same frame, creating a new DockNode+TabBar from the second window,
// then we need to hide the first one after the fact otherwise it would be visible as a standalone window for one frame.
if (node->HostWindow == NULL && node->Windows.Size == 2 && node->Windows[0]->WasActive == false)
{
node->Windows[0]->Hidden = true;
node->Windows[0]->HiddenFramesRegular = 1;
}
// When reactivating a node with one or two loose window, the window pos/size/viewport are authoritative over the node storage.
// In particular it is important we init the viewport from the first window so we don't create two viewports and drop one.
if (node->HostWindow == NULL && !node->IsDockSpace() && node->IsRootNode())
{
if (node->AutorityForPos == ImGuiDataAutority_Auto)
node->AutorityForPos = ImGuiDataAutority_Window;
if (node->AutorityForSize == ImGuiDataAutority_Auto)
node->AutorityForSize = ImGuiDataAutority_Window;
if (node->AutorityForViewport == ImGuiDataAutority_Auto)
node->AutorityForViewport = ImGuiDataAutority_Window;
}
// Add to tab bar if requested
if (add_to_tab_bar)
{
if (node->TabBar == NULL)
{
node->TabBar = IM_NEW(ImGuiTabBar)();
node->TabBar->SelectedTabId = node->TabBar->NextSelectedTabId = node->SelectedTabID;
// Add existing windows
for (int n = 0; n < node->Windows.Size - 1; n++)
TabBarAddTab(node->TabBar, ImGuiTabItemFlags_None, node->Windows[n]);
}
TabBarAddTab(node->TabBar, ImGuiTabItemFlags_Unsorted, window);
}
DockNodeUpdateVisibleFlag(node);
// Update this without waiting for the next time we Begin() in the window, so our host window will have the proper title bar color on its first frame.
if (node->HostWindow)
UpdateWindowParentAndRootLinks(window, window->Flags | ImGuiWindowFlags_ChildWindow, node->HostWindow);
}
static void ImGui::DockNodeRemoveWindow(ImGuiDockNode* node, ImGuiWindow* window, ImGuiID save_dock_id)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(window->DockNode == node);
//IM_ASSERT(window->RootWindow == node->HostWindow);
//IM_ASSERT(window->LastFrameActive < g.FrameCount); // We may call this from Begin()
IM_ASSERT(save_dock_id == 0 || save_dock_id == node->ID);
window->DockNode = NULL;
window->DockIsActive = window->DockTabWantClose = false;
window->DockId = save_dock_id;
UpdateWindowParentAndRootLinks(window, window->Flags & ~ImGuiWindowFlags_ChildWindow, NULL); // Update immediately
// Remove window
bool erased = false;
for (int n = 0; n < node->Windows.Size; n++)
if (node->Windows[n] == window)
{
node->Windows.erase(node->Windows.Data + n);
erased = true;
break;
}
IM_ASSERT(erased);
if (node->VisibleWindow == window)
node->VisibleWindow = NULL;
// Remove tab and possibly tab bar
node->WantHiddenTabBarUpdate = true;
if (node->TabBar)
{
TabBarRemoveTab(node->TabBar, window->ID);
const int tab_count_threshold_for_tab_bar = node->IsCentralNode ? 1 : 2;
if (node->Windows.Size < tab_count_threshold_for_tab_bar)
{
IM_DELETE(node->TabBar);
node->TabBar = NULL;
}
}
if (node->Windows.Size == 0 && !node->IsCentralNode && window->DockId != node->ID)
{
// Automatic dock node delete themselves if they are not holding at least one tab
DockContextRemoveNode(&g, node, true);
return;
}
if (node->Windows.Size == 1 && !node->IsCentralNode && node->HostWindow)
{
ImGuiWindow* remaining_window = node->Windows[0];
if (node->HostWindow->ViewportOwned && node->IsRootNode())
{
// Transfer viewport back to the remaining loose window
IM_ASSERT(node->HostWindow->Viewport->Window == node->HostWindow);
node->HostWindow->Viewport->Window = remaining_window;
node->HostWindow->Viewport->ID = remaining_window->ID;
}
remaining_window->Collapsed = node->HostWindow->Collapsed;
}
// Update visibility immediately is required so the DockNodeUpdateRemoveInactiveChilds() processing can reflect changes up the tree
DockNodeUpdateVisibleFlag(node);
}
static void ImGui::DockNodeMoveChildNodes(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
{
IM_ASSERT(dst_node->Windows.Size == 0);
dst_node->ChildNodes[0] = src_node->ChildNodes[0];
dst_node->ChildNodes[1] = src_node->ChildNodes[1];
if (dst_node->ChildNodes[0])
dst_node->ChildNodes[0]->ParentNode = dst_node;
if (dst_node->ChildNodes[1])
dst_node->ChildNodes[1]->ParentNode = dst_node;
dst_node->SplitAxis = src_node->SplitAxis;
dst_node->SizeRef = src_node->SizeRef;
src_node->ChildNodes[0] = src_node->ChildNodes[1] = NULL;
}
static void ImGui::DockNodeMoveWindows(ImGuiDockNode* dst_node, ImGuiDockNode* src_node)
{
// Insert tabs in the same orders as currently ordered (node->Windows isn't ordered)
IM_ASSERT(src_node && dst_node && dst_node != src_node);
ImGuiTabBar* src_tab_bar = src_node->TabBar;
if (src_tab_bar != NULL)
IM_ASSERT(src_node->Windows.Size == src_node->TabBar->Tabs.Size);
// If the dst_node is empty we can just move the entire tab bar (to preserve selection, scrolling, etc.)
bool move_tab_bar = (src_tab_bar != NULL) && (dst_node->TabBar == NULL);
if (move_tab_bar)
{
dst_node->TabBar = src_node->TabBar;
src_node->TabBar = NULL;
}
for (int n = 0; n < src_node->Windows.Size; n++)
{
ImGuiWindow* window = src_tab_bar ? src_tab_bar->Tabs[n].Window : src_node->Windows[n];
window->DockNode = NULL;
window->DockIsActive = false;
DockNodeAddWindow(dst_node, window, move_tab_bar ? false : true);
}
src_node->Windows.clear();
if (!move_tab_bar && src_node->TabBar)
{
if (dst_node->TabBar)
dst_node->TabBar->SelectedTabId = src_node->TabBar->SelectedTabId;
IM_DELETE(src_node->TabBar);
src_node->TabBar = NULL;
}
}
static void ImGui::DockNodeApplyPosSizeToWindows(ImGuiDockNode* node)
{
for (int n = 0; n < node->Windows.Size; n++)
{
node->Windows[n]->Pos = node->Pos;
node->Windows[n]->SizeFull = node->Size;
}
}
static void ImGui::DockNodeHideHostWindow(ImGuiDockNode* node)
{
if (node->HostWindow)
{
if (node->HostWindow->DockNodeAsHost == node)
node->HostWindow->DockNodeAsHost = NULL;
node->HostWindow = NULL;
}
if (node->Windows.Size == 1)
{
node->VisibleWindow = node->Windows[0];
node->Windows[0]->DockIsActive = false;
}
if (node->TabBar)
{
IM_DELETE(node->TabBar);
node->TabBar = NULL;
}
}
struct ImGuiDockNodeUpdateScanResults
{
ImGuiDockNode* CentralNode;
ImGuiDockNode* FirstNodeWithWindows;
int CountNodesWithWindows;
//ImGuiWindowClass WindowClassForMerges;
ImGuiDockNodeUpdateScanResults() { CentralNode = FirstNodeWithWindows = NULL; CountNodesWithWindows = 0; }
};
static void DockNodeUpdateScanRec(ImGuiDockNode* node, ImGuiDockNodeUpdateScanResults* results)
{
if (node->Windows.Size > 0)
{
if (results->FirstNodeWithWindows == NULL)
results->FirstNodeWithWindows = node;
results->CountNodesWithWindows++;
}
if (node->IsCentralNode)
{
IM_ASSERT(results->CentralNode == NULL); // Should be only one
IM_ASSERT(node->IsLeafNode() && "If you get this assert: please submit .ini file + repro of actions leading to this.");
results->CentralNode = node;
}
if (results->CountNodesWithWindows > 1 && results->CentralNode != NULL)
return;
if (node->ChildNodes[0])
DockNodeUpdateScanRec(node->ChildNodes[0], results);
if (node->ChildNodes[1])
DockNodeUpdateScanRec(node->ChildNodes[1], results);
}
// - Remove inactive windows/nodes.
// - Update visibility flag.
static void ImGui::DockNodeUpdateVisibleFlagAndInactiveChilds(ImGuiDockNode* node)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(node->ParentNode == NULL || node->ParentNode->ChildNodes[0] == node || node->ParentNode->ChildNodes[1] == node);
// Inherit most flags
ImGuiDockNodeFlags flags_to_inherit = ~0 & ~ImGuiDockNodeFlags_Dockspace;
if (node->ParentNode)
node->Flags = node->ParentNode->Flags & flags_to_inherit;
// Recurse into children
// There is the possibility that one of our child becoming empty will delete itself and moving its sibling contents into 'node'.
// If 'node->ChildNode[0]' delete itself, then 'node->ChildNode[1]->Windows' will be moved into 'node'
// If 'node->ChildNode[1]' delete itself, then 'node->ChildNode[0]->Windows' will be moved into 'node' and the "remove inactive windows" loop will have run twice on those windows (harmless)
if (node->ChildNodes[0])
DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[0]);
if (node->ChildNodes[1])
DockNodeUpdateVisibleFlagAndInactiveChilds(node->ChildNodes[1]);
// Remove inactive windows
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
ImGuiWindow* window = node->Windows[window_n];
IM_ASSERT(window->DockNode == node);
bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
bool remove = false;
remove |= node_was_active && (window->LastFrameActive + 1 < g.FrameCount);
remove |= node_was_active && (node->WantCloseAll || node->WantCloseTabID == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument); // Submit all _expected_ closure from last frame
remove |= (window->DockTabWantClose);
if (!remove)
continue;
window->DockTabWantClose = false;
if (node->Windows.Size == 1 && !node->IsCentralNode)
{
DockNodeHideHostWindow(node);
DockNodeRemoveWindow(node, window, node->ID); // Will delete the node so it'll be invalid on return
return;
}
DockNodeRemoveWindow(node, window, node->ID);
window_n--;
}
// Auto-hide tab bar option
if (node->WantHiddenTabBarUpdate && node->Windows.Size == 1 && (node->Flags & ImGuiDockNodeFlags_AutoHideTabBar) && !node->IsHiddenTabBar)
node->WantHiddenTabBarToggle = true;
node->WantHiddenTabBarUpdate = false;
// Apply toggles at a single point of the frame (here!)
if (node->Windows.Size > 1)
node->IsHiddenTabBar = false;
else if (node->WantHiddenTabBarToggle)
node->IsHiddenTabBar ^= 1;
node->WantHiddenTabBarToggle = false;
DockNodeUpdateVisibleFlag(node);
}
static void ImGui::DockNodeUpdateVisibleFlag(ImGuiDockNode* node)
{
// Update visibility flag
bool is_visible = (node->ParentNode == 0) ? node->IsDockSpace() : node->IsCentralNode;
is_visible |= (node->Windows.Size > 0);
is_visible |= (node->ChildNodes[0] && node->ChildNodes[0]->IsVisible);
is_visible |= (node->ChildNodes[1] && node->ChildNodes[1]->IsVisible);
node->IsVisible = is_visible;
}
static void ImGui::DockNodeStartMouseMovingWindow(ImGuiDockNode* node, ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(node->WantMouseMove == true);
ImVec2 backup_active_click_offset = g.ActiveIdClickOffset;
StartMouseMovingWindow(window);
g.MovingWindow = window; // If we are docked into a non moveable root window, StartMouseMovingWindow() won't set g.MovingWindow. Override that decision.
node->WantMouseMove = false;
g.ActiveIdClickOffset = backup_active_click_offset;
}
static void ImGui::DockNodeUpdate(ImGuiDockNode* node)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(node->LastFrameActive != g.FrameCount);
node->LastFrameAlive = g.FrameCount;
node->CentralNode = node->OnlyNodeWithWindows = NULL;
if (node->IsRootNode())
{
DockNodeUpdateVisibleFlagAndInactiveChilds(node);
// FIXME-DOCK: Merge this scan into the one above.
// - Setup central node pointers
// - Find if there's only a single visible window in the hierarchy (in which case we need to display a regular title bar -> FIXME-DOCK: that last part is not done yet!)
ImGuiDockNodeUpdateScanResults results;
DockNodeUpdateScanRec(node, &results);
node->CentralNode = results.CentralNode;
node->OnlyNodeWithWindows = (results.CountNodesWithWindows == 1) ? results.FirstNodeWithWindows : NULL;
if (node->LastFocusedNodeID == 0 && results.FirstNodeWithWindows != NULL)
node->LastFocusedNodeID = results.FirstNodeWithWindows->ID;
// Copy the window class from of our first window so it can be used for proper dock filtering.
// When node has mixed windows, prioritize the class with the most constraint (CompatibleWithClassZero = false) as the reference to copy.
// FIXME-DOCK: We don't recurse properly, this code could be reworked to work from DockNodeUpdateScanRec.
if (ImGuiDockNode* first_node_with_windows = results.FirstNodeWithWindows)
{
node->WindowClass = first_node_with_windows->Windows[0]->WindowClass;
for (int n = 1; n < first_node_with_windows->Windows.Size; n++)
if (first_node_with_windows->Windows[n]->WindowClass.DockingAllowUnclassed == false)
{
node->WindowClass = first_node_with_windows->Windows[n]->WindowClass;
break;
}
}
}
// Early out for hidden root dock nodes (when all DockId references are in inactive windows, or there is only 1 floating window holding on the DockId)
if (node->Windows.Size <= 1 && node->IsRootNode() && node->IsLeafNode() && !node->IsDockSpace() && !g.IO.ConfigDockingTabBarOnSingleWindows)
{
if (node->Windows.Size == 1)
{
// Floating window pos/size is authoritative
ImGuiWindow* single_window = node->Windows[0];
node->Pos = single_window->Pos;
node->Size = single_window->SizeFull;
// Transfer focus immediately so when we revert to a regular window it is immediately selected
if (node->HostWindow && g.NavWindow == node->HostWindow)
FocusWindow(single_window);
if (node->HostWindow)
{
single_window->Viewport = node->HostWindow->Viewport;
single_window->ViewportId = node->HostWindow->ViewportId;
if (node->HostWindow->ViewportOwned)
{
single_window->Viewport->Window = single_window;
single_window->ViewportOwned = true;
}
}
}
DockNodeHideHostWindow(node);
node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto;
node->WantCloseAll = false;
node->WantCloseTabID = 0;
node->HasCloseButton = node->HasCollapseButton = false;
node->LastFrameActive = g.FrameCount;
if (node->WantMouseMove && node->Windows.Size == 1)
DockNodeStartMouseMovingWindow(node, node->Windows[0]);
return;
}
ImGuiWindow* host_window = NULL;
bool beginned_into_host_window = false;
if (node->IsDockSpace())
{
// [Explicit root dockspace node]
IM_ASSERT(node->HostWindow);
node->HasCloseButton = false;
node->HasCollapseButton = true;
host_window = node->HostWindow;
}
else
{
// [Automatic root or child nodes]
node->HasCloseButton = false;
node->HasCollapseButton = (node->Windows.Size > 0);
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
// FIXME-DOCK: Setting DockIsActive here means that for single active window in a leaf node, DockIsActive will be cleared until the next Begin() call.
ImGuiWindow* window = node->Windows[window_n];
window->DockIsActive = (node->Windows.Size > 1);
node->HasCloseButton |= window->HasCloseButton;
}
if (node->IsRootNode() && node->IsVisible)
{
ImGuiWindow* ref_window = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
// Sync Pos
if (node->AutorityForPos == ImGuiDataAutority_Window && ref_window)
SetNextWindowPos(ref_window->Pos);
else if (node->AutorityForPos == ImGuiDataAutority_DockNode)
SetNextWindowPos(node->Pos);
// Sync Size
if (node->AutorityForSize == ImGuiDataAutority_Window && ref_window)
SetNextWindowSize(ref_window->SizeFull);
else if (node->AutorityForSize == ImGuiDataAutority_DockNode)
SetNextWindowSize(node->Size);
// Sync Collapsed
if (node->AutorityForSize == ImGuiDataAutority_Window && ref_window)
SetNextWindowCollapsed(ref_window->Collapsed);
// Sync Viewport
if (node->AutorityForViewport == ImGuiDataAutority_Window && ref_window)
SetNextWindowViewport(ref_window->ViewportId);
SetNextWindowClass(&node->WindowClass);
// Begin into the host window
char window_label[20];
DockNodeGetHostWindowTitle(node, window_label, IM_ARRAYSIZE(window_label));
ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse | ImGuiWindowFlags_DockNodeHost;
window_flags |= ImGuiWindowFlags_NoFocusOnAppearing;
window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoCollapse;
window_flags |= ImGuiWindowFlags_NoTitleBar;
PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
Begin(window_label, NULL, window_flags);
PopStyleVar();
beginned_into_host_window = true;
node->HostWindow = host_window = g.CurrentWindow;
host_window->DockNodeAsHost = node;
host_window->DC.CursorPos = host_window->Pos;
node->Pos = host_window->Pos;
node->Size = host_window->Size;
// We set ImGuiWindowFlags_NoFocusOnAppearing because we don't want the host window to take full focus (e.g. steal NavWindow)
// But we still it bring it to the front of display. There's no way to choose this precise behavior via window flags.
// One simple case to ponder if: window A has a toggle to create windows B/C/D. Dock B/C/D together, clear the toggle and enable it again.
// When reappearing B/C/D will request focus and be moved to the top of the display pile, but they are not linked to the dock host window
// during the frame they appear. The dock host window would keep its old display order, and the sorting in EndFrame would move B/C/D back
// after the dock host window, losing their top-most status.
if (node->HostWindow->Appearing)
BringWindowToDisplayFront(node->HostWindow);
node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto;
}
else if (node->ParentNode)
{
node->HostWindow = host_window = node->ParentNode->HostWindow;
node->AutorityForPos = node->AutorityForSize = node->AutorityForViewport = ImGuiDataAutority_Auto;
}
if (node->WantMouseMove && node->HostWindow)
DockNodeStartMouseMovingWindow(node, node->HostWindow);
}
// Update focused node (the one whose title bar is highlight) within a node tree
if (node->IsSplitNode())
IM_ASSERT(node->TabBar == NULL);
if (node->IsRootNode())
if (g.NavWindow && g.NavWindow->RootWindowDockStop->DockNode && g.NavWindow->RootWindowDockStop->ParentWindow == host_window)
node->LastFocusedNodeID = g.NavWindow->RootWindowDockStop->DockNode->ID;
// We need to draw a background if requested by ImGuiDockNodeFlags_PassthruDockspace, but we will only know the correct pos/size after
// processing the resizing splitters. So we are using the DrawList channel splitting facility to submit drawing primitives out of order!
const bool render_dockspace_bg = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruDockspace) != 0;
if (render_dockspace_bg)
{
host_window->DrawList->ChannelsSplit(2);
host_window->DrawList->ChannelsSetCurrent(1);
}
// Register a hit-test hole in the window unless we are currently dragging a window that is compatible with our dockspace
const ImGuiDockNode* central_node = node->CentralNode;
const bool central_node_hole = node->IsRootNode() && host_window && (node->Flags & ImGuiDockNodeFlags_PassthruDockspace) != 0 && central_node != NULL && central_node->IsEmpty();
bool central_node_hole_register_hit_test_hole = central_node_hole;
if (central_node_hole)
if (const ImGuiPayload* payload = ImGui::GetDragDropPayload())
if (payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) && DockNodeIsDropAllowed(host_window, *(ImGuiWindow**)payload->Data))
central_node_hole_register_hit_test_hole = false;
if (central_node_hole_register_hit_test_hole)
{
// Add a little padding to match the "resize from edges" behavior and allow grabbing the splitter easily.
IM_ASSERT(node->IsDockSpace()); // We cannot pass this flag without the DockSpace() api. Testing this because we also setup the hole in host_window->ParentNode
ImRect central_hole(central_node->Pos, central_node->Pos + central_node->Size);
central_hole.Expand(ImVec2(-WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, -WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS));
if (central_node_hole && !central_hole.IsInverted())
{
SetWindowHitTestHole(host_window, central_hole.Min, central_hole.Max - central_hole.Min);
SetWindowHitTestHole(host_window->ParentWindow, central_hole.Min, central_hole.Max - central_hole.Min);
}
}
// Update position/size, process and draw resizing splitters
if (node->IsRootNode() && host_window)
{
DockNodeTreeUpdatePosSize(node, host_window->Pos, host_window->Size);
DockNodeTreeUpdateSplitter(node);
}
// Draw empty node background (currently can only be the Central Node)
if (host_window && node->IsEmpty() && node->IsVisible && !(node->Flags & ImGuiDockNodeFlags_PassthruDockspace))
host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_DockingEmptyBg));
// Draw whole dockspace background if ImGuiDockNodeFlags_PassthruDockspace if set.
if (render_dockspace_bg && node->IsVisible)
{
host_window->DrawList->ChannelsSetCurrent(0);
if (central_node_hole)
RenderRectFilledWithHole(host_window->DrawList, node->Rect(), central_node->Rect(), GetColorU32(ImGuiCol_WindowBg), 0.0f);
else
host_window->DrawList->AddRectFilled(node->Pos, node->Pos + node->Size, GetColorU32(ImGuiCol_WindowBg), 0.0f);
host_window->DrawList->ChannelsMerge();
}
// Draw and populate Tab Bar
if (host_window && node->Windows.Size > 0)
{
DockNodeUpdateTabBar(node, host_window);
if (node->TabBar->SelectedTabId)
node->SelectedTabID = node->TabBar->SelectedTabId;
}
else
{
node->WantCloseAll = false;
node->WantCloseTabID = 0;
node->IsFocused = false;
if (node->Windows.Size > 0)
node->SelectedTabID = node->Windows[0]->ID;
}
// Draw payload drop target
if (host_window && node->IsVisible)
if (node->IsRootNode() && (g.MovingWindow == NULL || g.MovingWindow->RootWindow != host_window))
BeginAsDockableDragDropTarget(host_window);
node->LastFrameActive = g.FrameCount;
// Recurse into children
if (host_window)
{
if (node->ChildNodes[0])
DockNodeUpdate(node->ChildNodes[0]);
if (node->ChildNodes[1])
DockNodeUpdate(node->ChildNodes[1]);
// End host window
if (beginned_into_host_window)
End();
}
// Render outer borders last (after the tab bar)
if (node->IsRootNode() && host_window)
RenderOuterBorders(host_window);
}
// Compare TabItem nodes given the last known DockOrder (will persist in .ini file as hint), used to sort tabs when multiple tabs are added on the same frame.
static int IMGUI_CDECL TabItemComparerByDockOrder(const void* lhs, const void* rhs)
{
ImGuiWindow* a = ((const ImGuiTabItem*)lhs)->Window;
ImGuiWindow* b = ((const ImGuiTabItem*)rhs)->Window;
if (int d = ((a->DockOrder == -1) ? INT_MAX : a->DockOrder) - ((b->DockOrder == -1) ? INT_MAX : b->DockOrder))
return d;
return (a->BeginOrderWithinContext - b->BeginOrderWithinContext);
}
static ImGuiID ImGui::DockNodeUpdateTabListMenu(ImGuiDockNode* node, ImGuiTabBar* tab_bar)
{
// Try to position the menu so it is more likely to stays within the same viewport
ImGuiID ret_tab_id = 0;
SetNextWindowPos(ImVec2(node->Pos.x, node->Pos.y + GetFrameHeight()));
if (BeginPopup("#TabListMenu"))
{
node->IsFocused = true;
if (tab_bar->Tabs.Size == 1)
{
if (MenuItem("Hide tab bar", NULL, node->IsHiddenTabBar))
node->WantHiddenTabBarToggle = true;
}
else
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
IM_ASSERT(tab->Window != NULL);
if (Selectable(tab->Window->Name, tab->ID == tab_bar->SelectedTabId))
ret_tab_id = tab->ID;
SameLine();
Text(" ");
}
}
EndPopup();
}
return ret_tab_id;
}
static void ImGui::DockNodeUpdateTabBar(ImGuiDockNode* node, ImGuiWindow* host_window)
{
ImGuiContext& g = *GImGui;
ImGuiStyle& style = g.Style;
const bool node_was_active = (node->LastFrameActive + 1 == g.FrameCount);
const bool closed_all = node->WantCloseAll && node_was_active;
const ImGuiID closed_one = node->WantCloseTabID && node_was_active;
node->WantCloseAll = false;
node->WantCloseTabID = 0;
// Decide if we should use a focused title bar color
bool is_focused = false;
ImGuiDockNode* root_node = DockNodeGetRootNode(node);
if (g.NavWindowingTarget)
is_focused = (g.NavWindowingTarget->DockNode == node);
else if (g.NavWindow && g.NavWindow->RootWindowForTitleBarHighlight == host_window->RootWindow && root_node->LastFocusedNodeID == node->ID)
is_focused = true;
// Hidden tab bar will show a triangle on the upper-left (in Begin)
if (node->IsHiddenTabBar)
{
node->VisibleWindow = (node->Windows.Size > 0) ? node->Windows[0] : NULL;
node->IsFocused = is_focused;
if (is_focused)
node->LastFrameFocused = g.FrameCount;
if (node->VisibleWindow)
{
// Notify root of visible window (used to display title in OS task bar)
if (is_focused || root_node->VisibleWindow == NULL)
root_node->VisibleWindow = node->VisibleWindow;
if (node->TabBar)
node->TabBar->VisibleTabId = node->VisibleWindow->ID;
}
return;
}
// Move ourselves to the Menu layer (so we can be accessed by tapping Alt) + undo SkipItems flag in order to draw over the title bar even if the window is collapsed
bool backup_skip_item = host_window->SkipItems;
if (!node->IsDockSpace())
{
host_window->SkipItems = false;
host_window->DC.NavLayerCurrent = ImGuiNavLayer_Menu;
host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Menu);
}
PushID(node->ID);
ImGuiTabBar* tab_bar = node->TabBar;
bool tab_bar_is_recreated = (tab_bar == NULL); // Tab bar are automatically destroyed when a node gets hidden
if (tab_bar == NULL)
tab_bar = node->TabBar = IM_NEW(ImGuiTabBar)();
ImGuiID focus_tab_id = 0;
node->IsFocused = is_focused;
// Collapse button changes shape and display a list
if (IsPopupOpen("#TabListMenu"))
{
if (ImGuiID tab_id = DockNodeUpdateTabListMenu(node, tab_bar))
focus_tab_id = tab_bar->NextSelectedTabId = tab_id;
is_focused |= node->IsFocused;
}
// Title bar
if (is_focused)
node->LastFrameFocused = g.FrameCount;
ImRect title_bar_rect = ImRect(node->Pos, node->Pos + ImVec2(node->Size.x, g.FontSize + style.FramePadding.y * 2.0f));
ImU32 title_bar_col = GetColorU32(host_window->Collapsed ? ImGuiCol_TitleBgCollapsed : is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg);
host_window->DrawList->AddRectFilled(title_bar_rect.Min, title_bar_rect.Max, title_bar_col, host_window->WindowRounding, ImDrawCornerFlags_Top);
// Collapse button
if (CollapseButton(host_window->GetID("#COLLAPSE"), title_bar_rect.Min, node))
OpenPopup("#TabListMenu");
if (IsItemActive())
focus_tab_id = tab_bar->SelectedTabId;
// Submit new tabs and apply NavWindow focus back to the tab bar. They will be added as Unsorted and sorted below based on relative DockOrder value.
const int tabs_count_old = tab_bar->Tabs.Size;
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
ImGuiWindow* window = node->Windows[window_n];
if (g.NavWindow && g.NavWindow->RootWindowDockStop == window)
tab_bar->SelectedTabId = window->ID;
if (TabBarFindTabByID(tab_bar, window->ID) == NULL)
TabBarAddTab(tab_bar, ImGuiTabItemFlags_Unsorted, window);
}
// If multiple tabs are appearing on the same frame, sort them based on their persistent DockOrder value
int tabs_unsorted_start = tab_bar->Tabs.Size;
for (int tab_n = tab_bar->Tabs.Size - 1; tab_n >= 0 && (tab_bar->Tabs[tab_n].Flags & ImGuiTabItemFlags_Unsorted); tab_n--)
{
tab_bar->Tabs[tab_n].Flags &= ~ImGuiTabItemFlags_Unsorted;
tabs_unsorted_start = tab_n;
}
//printf("[%05d] Sorting %d new appearing tabs\n", g.FrameCount, tab_bar->Tabs.Size - tabs_unsorted_start);
if (tab_bar->Tabs.Size > tabs_unsorted_start + 1)
ImQsort(tab_bar->Tabs.Data + tabs_unsorted_start, tab_bar->Tabs.Size - tabs_unsorted_start, sizeof(ImGuiTabItem), TabItemComparerByDockOrder);
// Selected newly added tabs, or persistent tab ID if the tab bar was just recreated
if (tab_bar_is_recreated && TabBarFindTabByID(tab_bar, node->SelectedTabID) != NULL)
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = node->SelectedTabID;
else if (tab_bar->Tabs.Size > tabs_count_old)
tab_bar->SelectedTabId = tab_bar->NextSelectedTabId = tab_bar->Tabs.back().Window->ID;
// Begin tab bar
const ImRect tab_bar_rect = DockNodeCalcTabBarRect(node);
ImGuiTabBarFlags tab_bar_flags = ImGuiTabBarFlags_Reorderable | ImGuiTabBarFlags_AutoSelectNewTabs; // | ImGuiTabBarFlags_NoTabListScrollingButtons);
tab_bar_flags |= ImGuiTabBarFlags_SaveSettings | ImGuiTabBarFlags_DockNode;
if (!host_window->Collapsed && is_focused)
tab_bar_flags |= ImGuiTabBarFlags_IsFocused;
BeginTabBarEx(tab_bar, tab_bar_rect, tab_bar_flags, node);
//host_window->DrawList->AddRect(tab_bar_rect.Min, tab_bar_rect.Max, IM_COL32(255,0,255,255));
// Submit actual tabs
node->VisibleWindow = NULL;
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
ImGuiWindow* window = node->Windows[window_n];
if ((closed_all || closed_one == window->ID) && window->HasCloseButton && !(window->Flags & ImGuiWindowFlags_UnsavedDocument))
continue;
if (window->LastFrameActive + 1 >= g.FrameCount || !node_was_active)
{
ImGuiTabItemFlags tab_item_flags = 0;
if (window->Flags & ImGuiWindowFlags_UnsavedDocument)
tab_item_flags |= ImGuiTabItemFlags_UnsavedDocument;
if (tab_bar->Flags & ImGuiTabBarFlags_NoCloseWithMiddleMouseButton)
tab_item_flags |= ImGuiTabItemFlags_NoCloseWithMiddleMouseButton;
bool tab_open = true;
TabItemEx(tab_bar, window->Name, window->HasCloseButton ? &tab_open : NULL, tab_item_flags, window);
if (!tab_open)
node->WantCloseTabID = window->ID;
if (tab_bar->VisibleTabId == window->ID)
node->VisibleWindow = window;
// Store last item data so it can be queried with IsItemXXX functions after the user Begin() call
window->DockTabItemStatusFlags = host_window->DC.LastItemStatusFlags;
window->DockTabItemRect = host_window->DC.LastItemRect;
// Update navigation ID on menu layer
if (g.NavWindow && g.NavWindow->RootWindowDockStop == window && (window->DC.NavLayerActiveMask & (1 << 1)) == 0)
host_window->NavLastIds[1] = window->ID;
}
}
// Notify root of visible window (used to display title in OS task bar)
if (node->VisibleWindow)
if (is_focused || root_node->VisibleWindow == NULL)
root_node->VisibleWindow = node->VisibleWindow;
// Close button (after VisibleWindow was updated)
// Note that VisibleWindow may have been overrided by CTRL+Tabbing, so VisibleWindow->ID may be != from tab_bar->SelectedTabId
if (node->VisibleWindow)
{
if (!node->VisibleWindow->HasCloseButton)
{
PushItemFlag(ImGuiItemFlags_Disabled, true);
PushStyleColor(ImGuiCol_Text, style.Colors[ImGuiCol_Text] * ImVec4(1.0f,1.0f,1.0f,0.5f));
}
const float rad = g.FontSize * 0.5f;
if (CloseButton(host_window->GetID("#CLOSE"), title_bar_rect.GetTR() + ImVec2(-style.FramePadding.x - rad, style.FramePadding.y + rad), rad + 1))
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, tab_bar->VisibleTabId))
{
node->WantCloseTabID = tab->ID;
TabBarCloseTab(tab_bar, tab);
}
//if (IsItemActive())
// focus_tab_id = tab_bar->SelectedTabId;
if (!node->VisibleWindow->HasCloseButton)
{
PopStyleColor();
PopItemFlag();
}
}
// When clicking on the title bar outside of tabs, we still focus the selected tab for that node
if (g.HoveredWindow == host_window && g.HoveredId == 0 && IsMouseHoveringRect(title_bar_rect.Min, title_bar_rect.Max))
{
if (IsMouseClicked(0))
{
focus_tab_id = tab_bar->SelectedTabId;
// Forward moving request to selected window
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
StartMouseMovingWindow(tab->Window);
}
}
// Forward focus from host node to selected window
//if (is_focused && g.NavWindow == host_window && !g.NavWindowingTarget)
// focus_tab_id = tab_bar->SelectedTabId;
// When clicked on a tab we requested focus to the docked child
// This overrides the value set by "forward focus from host node to selected window".
if (tab_bar->NextSelectedTabId)
focus_tab_id = tab_bar->NextSelectedTabId;
// Apply navigation focus
if (focus_tab_id != 0)
if (ImGuiTabItem* tab = TabBarFindTabByID(tab_bar, focus_tab_id))
{
FocusWindow(tab->Window);
NavInitWindow(tab->Window, false);
}
EndTabBar();
PopID();
// Restore SkipItems flag
if (!node->IsDockSpace())
{
host_window->DC.NavLayerCurrent = ImGuiNavLayer_Main;
host_window->DC.NavLayerCurrentMask = (1 << ImGuiNavLayer_Main);
host_window->SkipItems = backup_skip_item;
}
}
static bool DockNodeIsDropAllowedOne(ImGuiWindow* payload, ImGuiWindow* host_window)
{
if (host_window->DockNodeAsHost && host_window->DockNodeAsHost->IsDockSpace() && payload->BeginOrderWithinContext < host_window->BeginOrderWithinContext)
return false;
ImGuiWindowClass* host_class = host_window->DockNodeAsHost ? &host_window->DockNodeAsHost->WindowClass : &host_window->WindowClass;
ImGuiWindowClass* payload_class = &payload->WindowClass;
if (host_class->ClassId != payload_class->ClassId)
{
if (host_class->ClassId != 0 && host_class->DockingAllowUnclassed && payload_class->ClassId == 0)
return true;
if (payload_class->ClassId != 0 && payload_class->DockingAllowUnclassed && host_class->ClassId == 0)
return true;
return false;
}
return true;
}
static bool ImGui::DockNodeIsDropAllowed(ImGuiWindow* host_window, ImGuiWindow* root_payload)
{
if (root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode())
return true;
const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows.Size : 1;
for (int payload_n = 0; payload_n < payload_count; payload_n++)
{
ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->Windows[payload_n] : root_payload;
if (DockNodeIsDropAllowedOne(payload, host_window))
return true;
}
return false;
}
static ImRect ImGui::DockNodeCalcTabBarRect(const ImGuiDockNode* node)
{
ImGuiContext& g = *GImGui;
ImRect r = ImRect(node->Pos.x, node->Pos.y, node->Pos.x + node->Size.x, node->Pos.y + (g.FontSize + g.Style.FramePadding.y * 2.0f));
if (node->HasCollapseButton)
r.Min.x += g.Style.FramePadding.x + g.FontSize; // + g.Style.ItemInnerSpacing.x; // <-- Adding ItemInnerSpacing makes the title text moves slightly when in a tab bar. Instead we adjusted RenderArrowDockMenu()
// In DockNodeUpdateTabBar() we currently display a disabled close button even if there is none.
r.Max.x -= g.Style.FramePadding.x + g.FontSize + 1.0f;
return r;
}
void ImGui::DockNodeCalcSplitRects(ImVec2& pos_old, ImVec2& size_old, ImVec2& pos_new, ImVec2& size_new, ImGuiDir dir, ImVec2 size_new_desired)
{
ImGuiContext& g = *GImGui;
const float dock_spacing = g.Style.ItemInnerSpacing.x;
const ImGuiAxis axis = (dir == ImGuiDir_Left || dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
pos_new[axis ^ 1] = pos_old[axis ^ 1];
size_new[axis ^ 1] = size_old[axis ^ 1];
// Distribute size on given axis (with a desired size or equally)
const float w_avail = size_old[axis] - dock_spacing;
if (size_new_desired[axis] > 0.0f && size_new_desired[axis] <= w_avail * 0.5f)
{
size_new[axis] = size_new_desired[axis];
size_old[axis] = (float)(int)(w_avail - size_new[axis]);
}
else
{
size_new[axis] = (float)(int)(w_avail * 0.5f);
size_old[axis] = (float)(int)(w_avail - size_new[axis]);
}
// Position each node
if (dir == ImGuiDir_Right || dir == ImGuiDir_Down)
{
pos_new[axis] = pos_old[axis] + size_old[axis] + dock_spacing;
}
else if (dir == ImGuiDir_Left || dir == ImGuiDir_Up)
{
pos_new[axis] = pos_old[axis];
pos_old[axis] = pos_new[axis] + size_new[axis] + dock_spacing;
}
}
// Retrieve the drop rectangles for a given direction or for the center + perform hit testing.
bool ImGui::DockNodeCalcDropRects(const ImRect& parent, ImGuiDir dir, ImRect& out_r, bool outer_docking)
{
ImGuiContext& g = *GImGui;
const float parent_smaller_axis = ImMin(parent.GetWidth(), parent.GetHeight());
const float hs_for_central_nodes = ImMin(g.FontSize * 1.5f, ImMax(g.FontSize * 0.5f, parent_smaller_axis / 8.0f));
float hs_w; // Half-size, longer axis
float hs_h; // Half-size, smaller axis
ImVec2 off; // Distance from edge or center
if (outer_docking)
{
//hs_w = ImFloor(ImClamp(parent_smaller_axis - hs_for_central_nodes * 4.0f, g.FontSize * 0.5f, g.FontSize * 8.0f));
//hs_h = ImFloor(hs_w * 0.15f);
//off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 1.4f - hs_h));
hs_w = ImFloor(hs_for_central_nodes * 1.50f);
hs_h = ImFloor(hs_for_central_nodes * 0.80f);
off = ImVec2(ImFloor(parent.GetWidth() * 0.5f - GetFrameHeightWithSpacing() * 0.0f - hs_h), ImFloor(parent.GetHeight() * 0.5f - GetFrameHeightWithSpacing() * 0.0f - hs_h));
}
else
{
hs_w = ImFloor(hs_for_central_nodes);
hs_h = ImFloor(hs_for_central_nodes * 0.90f);
off = ImVec2(ImFloor(hs_w * 2.40f), ImFloor(hs_w * 2.40f));
}
ImVec2 c = ImFloor(parent.GetCenter());
if (dir == ImGuiDir_None) { out_r = ImRect(c.x - hs_w, c.y - hs_w, c.x + hs_w, c.y + hs_w); }
else if (dir == ImGuiDir_Up) { out_r = ImRect(c.x - hs_w, c.y - off.y - hs_h, c.x + hs_w, c.y - off.y + hs_h); }
else if (dir == ImGuiDir_Down) { out_r = ImRect(c.x - hs_w, c.y + off.y - hs_h, c.x + hs_w, c.y + off.y + hs_h); }
else if (dir == ImGuiDir_Left) { out_r = ImRect(c.x - off.x - hs_h, c.y - hs_w, c.x - off.x + hs_h, c.y + hs_w); }
else if (dir == ImGuiDir_Right) { out_r = ImRect(c.x + off.x - hs_h, c.y - hs_w, c.x + off.x + hs_h, c.y + hs_w); }
ImRect hit_r = out_r;
if (!outer_docking)
{
// Custom hit testing for the 5-way selection, designed to reduce flickering when moving diagonally between sides
hit_r.Expand(ImFloor(hs_w * 0.30f));
ImVec2 mouse_delta = (g.IO.MousePos - c);
float mouse_delta_len2 = ImLengthSqr(mouse_delta);
float r_threshold_center = hs_w * 1.4f;
float r_threshold_sides = hs_w * (1.4f + 1.2f);
if (mouse_delta_len2 < r_threshold_center * r_threshold_center)
return (dir == ImGuiDir_None);
if (mouse_delta_len2 < r_threshold_sides * r_threshold_sides)
return (dir == ImGetDirQuadrantFromDelta(mouse_delta.x, mouse_delta.y));
}
return hit_r.Contains(g.IO.MousePos);
}
// host_node may be NULL if the window doesn't have a DockNode already.
static bool ImGui::DockNodePreviewDockCalc(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, ImGuiDockPreviewData* data, bool is_explicit_target, bool is_outer_docking)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.CurrentWindow == host_window); // Because we rely on font size to calculate tab sizes
// There is an edge case when docking into a dockspace which only has inactive nodes.
// In this case DockNodeTreeFindNodeByPos() will have selected a leaf node which is inactive.
// Because the inactive leaf node doesn't have proper pos/size yet, we'll use the root node as reference.
ImGuiDockNode* ref_node_for_rect = (host_node && !host_node->IsVisible) ? DockNodeGetRootNode(host_node) : host_node;
if (ref_node_for_rect)
IM_ASSERT(ref_node_for_rect->IsVisible);
// Build a tentative future node (reuse same structure because it is practical)
data->FutureNode.HasCloseButton = (host_node ? host_node->HasCloseButton : host_window->HasCloseButton) || (root_payload->HasCloseButton);
data->FutureNode.HasCollapseButton = host_node ? true : ((host_window->Flags & ImGuiWindowFlags_NoCollapse) == 0);
data->FutureNode.Pos = host_node ? ref_node_for_rect->Pos : host_window->Pos;
data->FutureNode.Size = host_node ? ref_node_for_rect->Size : host_window->Size;
// Figure out here we are allowed to dock
const bool src_is_visibly_splitted = root_payload->DockNodeAsHost && root_payload->DockNodeAsHost->IsSplitNode() && (root_payload->DockNodeAsHost->OnlyNodeWithWindows == NULL);
data->IsCenterAvailable = !is_outer_docking;
if (src_is_visibly_splitted && (!host_node || !host_node->IsEmpty()))
data->IsCenterAvailable = false;
if (host_node && (host_node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode) && host_node->IsCentralNode)
data->IsCenterAvailable = false;
data->IsSidesAvailable = true;
if ((host_node && (host_node->Flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
data->IsSidesAvailable = false;
if (!is_outer_docking && host_node && host_node->ParentNode == NULL && host_node->IsCentralNode)
data->IsSidesAvailable = false;
// Calculate drop shapes geometry for allowed splitting directions
IM_ASSERT(ImGuiDir_None == -1);
data->SplitNode = host_node;
data->SplitDir = ImGuiDir_None;
data->IsSplitDirExplicit = false;
if (!host_window->Collapsed)
for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
{
if (dir == ImGuiDir_None && !data->IsCenterAvailable)
continue;
if (dir != ImGuiDir_None && !data->IsSidesAvailable)
continue;
if (DockNodeCalcDropRects(data->FutureNode.Rect(), (ImGuiDir)dir, data->DropRectsDraw[dir+1], is_outer_docking))
{
data->SplitDir = (ImGuiDir)dir;
data->IsSplitDirExplicit = true;
}
}
// When docking without holding Shift, we only allow and preview docking when hovering over a drop rect or over the title bar
data->IsDropAllowed = (data->SplitDir != ImGuiDir_None) || (data->IsCenterAvailable);
if (!is_explicit_target && !data->IsSplitDirExplicit && !g.IO.ConfigDockingWithShift)
data->IsDropAllowed = false;
// Calculate split area
data->SplitRatio = 0.0f;
if (data->SplitDir != ImGuiDir_None)
{
ImGuiDir split_dir = data->SplitDir;
ImGuiAxis split_axis = (split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Right) ? ImGuiAxis_X : ImGuiAxis_Y;
ImVec2 pos_new, pos_old = data->FutureNode.Pos;
ImVec2 size_new, size_old = data->FutureNode.Size;
DockNodeCalcSplitRects(pos_old, size_old, pos_new, size_new, split_dir, root_payload->Size);
// Calculate split ratio so we can pass it down the docking request
float split_ratio = ImSaturate(size_new[split_axis] / data->FutureNode.Size[split_axis]);
data->FutureNode.Pos = pos_new;
data->FutureNode.Size = size_new;
data->SplitRatio = (split_dir == ImGuiDir_Right || split_dir == ImGuiDir_Down) ? (1.0f - split_ratio) : (split_ratio);
}
return data->IsSplitDirExplicit;
}
static void ImGui::DockNodePreviewDockRender(ImGuiWindow* host_window, ImGuiDockNode* host_node, ImGuiWindow* root_payload, const ImGuiDockPreviewData* data)
{
ImGuiContext& g = *GImGui;
// With this option, we only display the preview on the target viewport, and the payload viewport is made transparent.
// To compensate for the single layer obstructed by the payload, we'll increase the alpha of the preview nodes.
const bool is_transparent_payload = g.IO.ConfigDockingTransparentPayload;
// In case the two windows involved are on different viewports, we will draw the overlay on each of them.
int overlay_draw_lists_count = 0;
ImDrawList* overlay_draw_lists[2];
overlay_draw_lists[overlay_draw_lists_count++] = GetOverlayDrawList(host_window->Viewport);
if (host_window->Viewport != root_payload->Viewport && !is_transparent_payload)
overlay_draw_lists[overlay_draw_lists_count++] = GetOverlayDrawList(root_payload->Viewport);
// Draw main preview rectangle
const ImU32 overlay_col_tabs = GetColorU32(ImGuiCol_TabActive);
const ImU32 overlay_col_main = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.60f : 0.40f);
const ImU32 overlay_col_drop = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 0.90f : 0.70f);
const ImU32 overlay_col_drop_hovered = GetColorU32(ImGuiCol_DockingPreview, is_transparent_payload ? 1.20f : 1.00f);
const ImU32 overlay_col_lines = GetColorU32(ImGuiCol_NavWindowingHighlight, is_transparent_payload ? 0.80f : 0.60f);
// Display area preview
const bool can_preview_tabs = (root_payload->DockNodeAsHost == NULL || root_payload->DockNodeAsHost->Windows.Size > 0);
if (data->IsDropAllowed)
{
ImRect overlay_rect = data->FutureNode.Rect();
if (data->SplitDir == ImGuiDir_None && can_preview_tabs)
overlay_rect.Min.y += GetFrameHeight();
if (data->SplitDir != ImGuiDir_None || data->IsCenterAvailable)
for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
overlay_draw_lists[overlay_n]->AddRectFilled(overlay_rect.Min, overlay_rect.Max, overlay_col_main, host_window->WindowRounding);
}
// Display tab shape/label preview unless we are splitting node (it generally makes the situation harder to read)
if (data->IsDropAllowed && can_preview_tabs && data->SplitDir == ImGuiDir_None && data->IsCenterAvailable)
{
// Compute target tab bar geometry so we can locate our preview tabs
ImRect tab_bar_rect = DockNodeCalcTabBarRect(&data->FutureNode);
ImVec2 tab_pos = tab_bar_rect.Min;
if (host_node && host_node->TabBar)
{
if (!host_node->IsHiddenTabBar)
tab_pos.x += host_node->TabBar->OffsetMax + g.Style.ItemInnerSpacing.x; // We don't use OffsetNewTab because when using non-persistent-order tab bar it is incremented with each Tab submission.
else
tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_node->Windows[0]->Name, host_node->Windows[0]->HasCloseButton).x;
}
else if (!(host_window->Flags & ImGuiWindowFlags_DockNodeHost))
{
tab_pos.x += g.Style.ItemInnerSpacing.x + TabItemCalcSize(host_window->Name, host_window->HasCloseButton).x; // Account for slight offset which will be added when changing from title bar to tab bar
}
// Draw tab shape/label preview (payload may be a loose window or a host window carrying multiple tabbed windows)
if (root_payload->DockNodeAsHost)
IM_ASSERT(root_payload->DockNodeAsHost->Windows.Size == root_payload->DockNodeAsHost->TabBar->Tabs.Size);
const int payload_count = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs.Size : 1;
for (int payload_n = 0; payload_n < payload_count; payload_n++)
{
// Calculate the tab bounding box for each payload window
ImGuiWindow* payload = root_payload->DockNodeAsHost ? root_payload->DockNodeAsHost->TabBar->Tabs[payload_n].Window : root_payload;
if (!DockNodeIsDropAllowedOne(payload, host_window))
continue;
ImVec2 tab_size = TabItemCalcSize(payload->Name, payload->HasCloseButton);
ImRect tab_bb(tab_pos.x, tab_pos.y, tab_pos.x + tab_size.x, tab_pos.y + tab_size.y);
tab_pos.x += tab_size.x + g.Style.ItemInnerSpacing.x;
for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
{
ImGuiTabItemFlags tab_flags = ImGuiTabItemFlags_Preview | ((payload->Flags & ImGuiWindowFlags_UnsavedDocument) ? ImGuiTabItemFlags_UnsavedDocument : 0);
if (!tab_bar_rect.Contains(tab_bb))
overlay_draw_lists[overlay_n]->PushClipRect(tab_bar_rect.Min, tab_bar_rect.Max);
TabItemBackground(overlay_draw_lists[overlay_n], tab_bb, tab_flags, overlay_col_tabs);
TabItemLabelAndCloseButton(overlay_draw_lists[overlay_n], tab_bb, tab_flags, g.Style.FramePadding, payload->Name, 0, 0);
if (!tab_bar_rect.Contains(tab_bb))
overlay_draw_lists[overlay_n]->PopClipRect();
}
}
}
// Display drop boxes
const float overlay_rounding = ImMax(3.0f, g.Style.FrameRounding);
for (int dir = ImGuiDir_None; dir < ImGuiDir_COUNT; dir++)
{
if (!data->DropRectsDraw[dir + 1].IsInverted())
{
ImRect draw_r = data->DropRectsDraw[dir + 1];
ImRect draw_r_in = draw_r;
draw_r_in.Expand(-2.0f);
ImU32 overlay_col = (data->SplitDir == (ImGuiDir)dir && data->IsSplitDirExplicit) ? overlay_col_drop_hovered : overlay_col_drop;
for (int overlay_n = 0; overlay_n < overlay_draw_lists_count; overlay_n++)
{
ImVec2 center = ImFloor(draw_r_in.GetCenter());
overlay_draw_lists[overlay_n]->AddRectFilled(draw_r.Min, draw_r.Max, overlay_col, overlay_rounding);
overlay_draw_lists[overlay_n]->AddRect(draw_r_in.Min, draw_r_in.Max, overlay_col_lines, overlay_rounding);
if (dir == ImGuiDir_Left || dir == ImGuiDir_Right)
overlay_draw_lists[overlay_n]->AddLine(ImVec2(center.x, draw_r_in.Min.y), ImVec2(center.x, draw_r_in.Max.y), overlay_col_lines);
if (dir == ImGuiDir_Up || dir == ImGuiDir_Down)
overlay_draw_lists[overlay_n]->AddLine(ImVec2(draw_r_in.Min.x, center.y), ImVec2(draw_r_in.Max.x, center.y), overlay_col_lines);
}
}
// Stop after ImGuiDir_None
if ((host_node && (host_node->Flags & ImGuiDockNodeFlags_NoSplit)) || g.IO.ConfigDockingNoSplit)
return;
}
}
//-----------------------------------------------------------------------------
// Docking: ImGuiDockNode Tree manipulation functions
//-----------------------------------------------------------------------------
void ImGui::DockNodeTreeSplit(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiAxis split_axis, int split_inheritor_child_idx, float split_ratio, ImGuiDockNode* new_node)
{
IM_ASSERT(split_axis != ImGuiAxis_None);
ImGuiDockNode* child_0 = (new_node && split_inheritor_child_idx != 0) ? new_node : DockContextAddNode(ctx, 0);
child_0->ParentNode = parent_node;
ImGuiDockNode* child_1 = (new_node && split_inheritor_child_idx != 1) ? new_node : DockContextAddNode(ctx, 0);
child_1->ParentNode = parent_node;
ImGuiDockNode* child_inheritor = (split_inheritor_child_idx == 0) ? child_0 : child_1;
DockNodeMoveChildNodes(child_inheritor, parent_node);
parent_node->ChildNodes[0] = child_0;
parent_node->ChildNodes[1] = child_1;
parent_node->ChildNodes[split_inheritor_child_idx]->VisibleWindow = parent_node->VisibleWindow;
parent_node->SplitAxis = split_axis;
parent_node->VisibleWindow = NULL;
float size_avail = (parent_node->Size[split_axis] - IMGUI_DOCK_SPLITTER_SIZE);
IM_ASSERT(size_avail > 0.0f);
child_0->SizeRef = child_1->SizeRef = parent_node->Size;
child_0->SizeRef[split_axis] = ImFloor(size_avail * split_ratio);
child_1->SizeRef[split_axis] = ImFloor(size_avail - child_0->SizeRef[split_axis]);
DockNodeMoveWindows(parent_node->ChildNodes[split_inheritor_child_idx], parent_node);
DockNodeTreeUpdatePosSize(parent_node, parent_node->Pos, parent_node->Size);
child_inheritor->IsCentralNode = parent_node->IsCentralNode;
child_inheritor->IsHiddenTabBar = parent_node->IsHiddenTabBar;
parent_node->IsCentralNode = false;
}
void ImGui::DockNodeTreeMerge(ImGuiContext* ctx, ImGuiDockNode* parent_node, ImGuiDockNode* merge_lead_child)
{
// When called from DockContextProcessUndockNode() it is possible that one of the child is NULL.
ImGuiDockNode* child_0 = parent_node->ChildNodes[0];
ImGuiDockNode* child_1 = parent_node->ChildNodes[1];
IM_ASSERT(child_0 || child_1);
IM_ASSERT(merge_lead_child == child_0 || merge_lead_child == child_1);
if ((child_0 && child_0->Windows.Size > 0) || (child_1 && child_1->Windows.Size > 0))
{
IM_ASSERT(parent_node->TabBar == NULL);
IM_ASSERT(parent_node->Windows.Size == 0);
}
ImVec2 backup_last_explicit_size = parent_node->SizeRef;
DockNodeMoveChildNodes(parent_node, merge_lead_child);
if (child_0)
{
DockNodeMoveWindows(parent_node, child_0); // Generally only 1 of the 2 child node will have windows
DockSettingsRenameNodeReferences(child_0->ID, parent_node->ID);
}
if (child_1)
{
DockNodeMoveWindows(parent_node, child_1);
DockSettingsRenameNodeReferences(child_1->ID, parent_node->ID);
}
DockNodeApplyPosSizeToWindows(parent_node);
parent_node->AutorityForPos = parent_node->AutorityForSize = parent_node->AutorityForViewport = ImGuiDataAutority_Auto;
parent_node->VisibleWindow = merge_lead_child->VisibleWindow;
parent_node->IsCentralNode = (child_0 && child_0->IsCentralNode) || (child_1 && child_1->IsCentralNode);
parent_node->IsHiddenTabBar = merge_lead_child->IsHiddenTabBar;
parent_node->SizeRef = backup_last_explicit_size;
if (child_0)
{
ctx->DockContext->Nodes.SetVoidPtr(child_0->ID, NULL);
IM_DELETE(child_0);
}
if (child_1)
{
ctx->DockContext->Nodes.SetVoidPtr(child_1->ID, NULL);
IM_DELETE(child_1);
}
}
// Update Pos/Size for a node hierarchy (don't affect child Windows yet)
void ImGui::DockNodeTreeUpdatePosSize(ImGuiDockNode* node, ImVec2 pos, ImVec2 size)
{
node->Pos = pos;
node->Size = size;
if (node->IsLeafNode())
return;
ImGuiDockNode* child_0 = node->ChildNodes[0];
ImGuiDockNode* child_1 = node->ChildNodes[1];
ImVec2 child_0_pos = pos, child_1_pos = pos;
ImVec2 child_0_size = size, child_1_size = size;
if (child_0->IsVisible && child_1->IsVisible)
{
const float spacing = IMGUI_DOCK_SPLITTER_SIZE;
const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
const float size_avail = ImMax(size[axis] - spacing, 0.0f);
// Size allocation policy
// 1) The first 0..WindowMinSize[axis]*2 are allocated evenly to both windows.
ImGuiContext& g = *GImGui;
const float size_min_each = ImFloor(ImMin(size_avail, g.Style.WindowMinSize[axis] * 2.0f) * 0.5f);
// 2) Process locked absolute size (during a splitter resize we preserve the child of nodes not touching the splitter edge)
IM_ASSERT(!(child_0->WantLockSizeOnce && child_1->WantLockSizeOnce));
if (child_0->WantLockSizeOnce)
{
child_0->WantLockSizeOnce = false;
child_0_size[axis] = child_0->SizeRef[axis] = child_0->Size[axis];
child_1_size[axis] = child_1->SizeRef[axis] = (size_avail - child_0_size[axis]);
}
else if (child_1->WantLockSizeOnce)
{
child_1->WantLockSizeOnce = false;
child_1_size[axis] = child_1->SizeRef[axis] = child_1->Size[axis];
child_0_size[axis] = child_0->SizeRef[axis] = (size_avail - child_1_size[axis]);
}
// 3) If one window is the central node (~ use remaining space, should be made explicit!), use explicit size from the other, and remainder for the central node
else if (child_1->IsCentralNode && child_0->SizeRef[axis] != 0.0f)
{
child_0_size[axis] = ImMin(size_avail - size_min_each, child_0->SizeRef[axis]);
child_1_size[axis] = (size_avail - child_0_size[axis]);
}
else if (child_0->IsCentralNode && child_1->SizeRef[axis] != 0.0f)
{
child_1_size[axis] = ImMin(size_avail - size_min_each, child_1->SizeRef[axis]);
child_0_size[axis] = (size_avail - child_1_size[axis]);
}
else
{
// 4) Otherwise distribute according to the relative ratio of each SizeRef value
float split_ratio = child_0->SizeRef[axis] / (child_0->SizeRef[axis] + child_1->SizeRef[axis]);
child_0_size[axis] = ImMax(size_min_each, ImFloor(size_avail * split_ratio + 0.5F));
child_1_size[axis] = (size_avail - child_0_size[axis]);
}
child_1_pos[axis] += spacing + child_0_size[axis];
}
if (child_0->IsVisible)
DockNodeTreeUpdatePosSize(child_0, child_0_pos, child_0_size);
if (child_1->IsVisible)
DockNodeTreeUpdatePosSize(child_1, child_1_pos, child_1_size);
}
static void DockNodeTreeUpdateSplitterFindTouchingNode(ImGuiDockNode* node, ImGuiAxis axis, int side, ImVector<ImGuiDockNode*>* touching_nodes)
{
if (node->IsLeafNode())
{
touching_nodes->push_back(node);
return;
}
if (node->ChildNodes[0]->IsVisible)
if (node->SplitAxis != axis || side == 0 || !node->ChildNodes[1]->IsVisible)
DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[0], axis, side, touching_nodes);
if (node->ChildNodes[1]->IsVisible)
if (node->SplitAxis != axis || side == 1 || !node->ChildNodes[0]->IsVisible)
DockNodeTreeUpdateSplitterFindTouchingNode(node->ChildNodes[1], axis, side, touching_nodes);
}
void ImGui::DockNodeTreeUpdateSplitter(ImGuiDockNode* node)
{
if (node->IsLeafNode())
return;
ImGuiContext& g = *GImGui;
ImGuiDockNode* child_0 = node->ChildNodes[0];
ImGuiDockNode* child_1 = node->ChildNodes[1];
if (child_0->IsVisible && child_1->IsVisible)
{
// Bounding box of the splitter cover the space between both nodes (w = Spacing, h = Size[xy^1] for when splitting horizontally)
const ImGuiAxis axis = (ImGuiAxis)node->SplitAxis;
IM_ASSERT(axis != ImGuiAxis_None);
ImRect bb;
bb.Min = child_0->Pos;
bb.Max = child_1->Pos;
bb.Min[axis] += child_0->Size[axis];
bb.Max[axis ^ 1] += child_1->Size[axis ^ 1];
//if (g.IO.KeyCtrl) GetOverlayDrawList(g.CurrentWindow->Viewport)->AddRect(bb.Min, bb.Max, IM_COL32(255,0,255,255));
if (node->Flags & ImGuiDockNodeFlags_NoResize)
{
ImGuiWindow* window = g.CurrentWindow;
window->DrawList->AddRectFilled(bb.Min, bb.Max, GetColorU32(ImGuiCol_Separator), g.Style.FrameRounding);
}
else
{
//bb.Min[axis] += 1; // Display a little inward so highlight doesn't connect with nearby tabs on the neighbor node.
//bb.Max[axis] -= 1;
PushID(node->ID);
// Gather list of nodes that are touching the splitter line. Find resizing limits based on those nodes.
ImVector<ImGuiDockNode*> touching_nodes[2];
float min_size = g.Style.WindowMinSize[axis];
float resize_limits[2];
resize_limits[0] = node->ChildNodes[0]->Pos[axis] + min_size;
resize_limits[1] = node->ChildNodes[1]->Pos[axis] + node->ChildNodes[1]->Size[axis] - min_size;
ImGuiID splitter_id = GetID("##Splitter");
if (g.ActiveId == splitter_id)
{
// Only process when splitter is active
DockNodeTreeUpdateSplitterFindTouchingNode(child_0, axis, 1, &touching_nodes[0]);
DockNodeTreeUpdateSplitterFindTouchingNode(child_1, axis, 0, &touching_nodes[1]);
for (int touching_node_n = 0; touching_node_n < touching_nodes[0].Size; touching_node_n++)
resize_limits[0] = ImMax(resize_limits[0], touching_nodes[0][touching_node_n]->Rect().Min[axis] + min_size);
for (int touching_node_n = 0; touching_node_n < touching_nodes[1].Size; touching_node_n++)
resize_limits[1] = ImMin(resize_limits[1], touching_nodes[1][touching_node_n]->Rect().Max[axis] - min_size);
/*
// [DEBUG] Render limits
ImDrawList* draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport());
for (int n = 0; n < 2; n++)
if (axis == ImGuiAxis_X)
draw_list->AddLine(ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y), ImVec2(resize_limits[n], node->ChildNodes[n]->Pos.y + node->ChildNodes[n]->Size.y), IM_COL32(255, 0, 255, 255), 3.0f);
else
draw_list->AddLine(ImVec2(node->ChildNodes[n]->Pos.x, resize_limits[n]), ImVec2(node->ChildNodes[n]->Pos.x + node->ChildNodes[n]->Size.x, resize_limits[n]), IM_COL32(255, 0, 255, 255), 3.0f);
*/
}
// Use a short delay before highlighting the splitter (and changing the mouse cursor) in order for regular mouse movement to not highlight many splitters
float cur_size_0 = child_0->Size[axis];
float cur_size_1 = child_1->Size[axis];
float min_size_0 = resize_limits[0] - child_0->Pos[axis];
float min_size_1 = child_1->Pos[axis] + child_1->Size[axis] - resize_limits[1];
if (SplitterBehavior(bb, GetID("##Splitter"), axis, &cur_size_0, &cur_size_1, min_size_0, min_size_1, WINDOWS_RESIZE_FROM_EDGES_HALF_THICKNESS, WINDOWS_RESIZE_FROM_EDGES_FEEDBACK_TIMER))
{
if (touching_nodes[0].Size > 0 && touching_nodes[1].Size > 0)
{
child_0->Size[axis] = child_0->SizeRef[axis] = cur_size_0;
child_1->Pos[axis] -= cur_size_1 - child_1->Size[axis];
child_1->Size[axis] = child_1->SizeRef[axis] = cur_size_1;
// Lock the size of every node that is a sibling of the node we are touching
// This might be less desirable if we can merge sibling of a same axis into the same parental level.
for (int side_n = 0; side_n < 2; side_n++)
for (int touching_node_n = 0; touching_node_n < touching_nodes[side_n].Size; touching_node_n++)
{
ImGuiDockNode* touching_node = touching_nodes[side_n][touching_node_n];
//ImDrawList* draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport());
//draw_list->AddRect(touching_node->Pos, touching_node->Pos + touching_node->Size, IM_COL32(255, 128, 0, 255));
while (touching_node->ParentNode != node)
{
if (touching_node->ParentNode->SplitAxis == axis)
{
// Mark other node so its size will be preserved during the upcoming call to DockNodeTreeUpdatePosSize().
ImGuiDockNode* node_to_preserve = touching_node->ParentNode->ChildNodes[side_n];
node_to_preserve->WantLockSizeOnce = true;
//draw_list->AddRect(touching_node->Pos, touching_node->Rect().Max, IM_COL32(255, 0, 0, 255));
//draw_list->AddRectFilled(node_to_preserve->Pos, node_to_preserve->Rect().Max, IM_COL32(0, 255, 0, 100));
}
touching_node = touching_node->ParentNode;
}
}
DockNodeTreeUpdatePosSize(child_0, child_0->Pos, child_0->Size);
DockNodeTreeUpdatePosSize(child_1, child_1->Pos, child_1->Size);
MarkIniSettingsDirty();
}
}
PopID();
}
}
if (child_0->IsVisible)
DockNodeTreeUpdateSplitter(child_0);
if (child_1->IsVisible)
DockNodeTreeUpdateSplitter(child_1);
}
ImGuiDockNode* ImGui::DockNodeTreeFindFallbackLeafNode(ImGuiDockNode* node)
{
if (node->IsLeafNode())
return node;
if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[0]))
return leaf_node;
if (ImGuiDockNode* leaf_node = DockNodeTreeFindFallbackLeafNode(node->ChildNodes[1]))
return leaf_node;
return NULL;
}
ImGuiDockNode* ImGui::DockNodeTreeFindNodeByPos(ImGuiDockNode* node, ImVec2 pos)
{
if (!node->IsVisible)
return NULL;
ImGuiContext& g = *GImGui;
const float dock_spacing = g.Style.ItemInnerSpacing.x;
ImRect r(node->Pos, node->Pos + node->Size);
r.Expand(dock_spacing * 0.5f);
bool inside = r.Contains(pos);
if (!inside)
return NULL;
if (node->IsLeafNode())
return node;
if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[0], pos))
return hovered_node;
if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(node->ChildNodes[1], pos))
return hovered_node;
// There is an edge case when docking into a dockspace which only has inactive nodes (because none of the windows are active)
// In this case we need to fallback into any leaf mode, possibly the central node.
if (node->IsDockSpace() && node->IsRootNode())
{
if (node->CentralNode && node->IsLeafNode()) // FIXME-20181220: We should not have to test for IsLeafNode() here but we have another bug to fix first.
return node->CentralNode;
return DockNodeTreeFindFallbackLeafNode(node);
}
return NULL;
}
//-----------------------------------------------------------------------------
// Docking: Public Functions (SetWindowDock, DockSpace, DockSpaceOverViewport)
//-----------------------------------------------------------------------------
void ImGui::SetWindowDock(ImGuiWindow* window, ImGuiID dock_id, ImGuiCond cond)
{
// Test condition (NB: bit 0 is always true) and clear flags for next time
if (cond && (window->SetWindowDockAllowFlags & cond) == 0)
return;
window->SetWindowDockAllowFlags &= ~(ImGuiCond_Once | ImGuiCond_FirstUseEver | ImGuiCond_Appearing);
if (window->DockId == dock_id)
return;
// If the user attempt to set a dock id that is a split node, we'll dig within to find a suitable docking spot
ImGuiContext* ctx = GImGui;
if (ImGuiDockNode* new_node = DockContextFindNodeByID(ctx, dock_id))
if (new_node->IsSplitNode())
{
// Policy: Find central node or latest focused node. We first move back to our root node.
new_node = DockNodeGetRootNode(new_node);
if (new_node->CentralNode)
dock_id = new_node->CentralNode->ID;
else
dock_id = new_node->LastFocusedNodeID;
}
if (window->DockId == dock_id)
return;
if (window->DockNode)
DockNodeRemoveWindow(window->DockNode, window, 0);
window->DockId = dock_id;
}
// Create an explicit dockspace node within an existing window. Also expose dock node flags and creates a CentralNode by default.
// The Central Node is always displayed even when empty and shrink/extend according to the requested size of its neighbors.
void ImGui::DockSpace(ImGuiID id, const ImVec2& size_arg, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
{
ImGuiContext* ctx = GImGui;
ImGuiContext& g = *ctx;
ImGuiWindow* window = GetCurrentWindow();
if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
return;
ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
if (!node)
{
node = DockContextAddNode(ctx, id);
node->IsCentralNode = true;
}
node->Flags = dockspace_flags;
node->WindowClass = window_class ? *window_class : ImGuiWindowClass();
// When a Dockspace transitioned form implicit to explicit this may be called a second time
// It is possible that the node has already been claimed by a docked window which appeared before the DockSpace() node, so we overwrite IsDockSpace again.
if (node->LastFrameActive == g.FrameCount && !(dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly))
{
IM_ASSERT(node->IsDockSpace() == false && "Cannot call DockSpace() twice a frame with the same ID");
node->Flags |= ImGuiDockNodeFlags_Dockspace;
return;
}
node->Flags |= ImGuiDockNodeFlags_Dockspace;
// Keep alive mode, this is allow windows docked into this node so stay docked even if they are not visible
if (dockspace_flags & ImGuiDockNodeFlags_KeepAliveOnly)
{
node->LastFrameAlive = g.FrameCount;
return;
}
const ImVec2 content_avail = GetContentRegionAvail();
ImVec2 size = ImFloor(size_arg);
if (size.x <= 0.0f)
size.x = ImMax(content_avail.x + size.x, 4.0f); // Arbitrary minimum child size (0.0f causing too much issues)
if (size.y <= 0.0f)
size.y = ImMax(content_avail.y + size.y, 4.0f);
node->Pos = window->DC.CursorPos;
node->Size = node->SizeRef = size;
SetNextWindowPos(node->Pos);
SetNextWindowSize(node->Size);
g.NextWindowData.PosUndock = false;
ImGuiWindowFlags window_flags = ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_DockNodeHost;
window_flags |= ImGuiWindowFlags_NoSavedSettings | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoTitleBar;
window_flags |= ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
char title[256];
ImFormatString(title, IM_ARRAYSIZE(title), "%s/DockSpace_%08X", window->Name, id);
if (node->Windows.Size > 0 || node->IsSplitNode())
PushStyleColor(ImGuiCol_ChildBg, IM_COL32(0, 0, 0, 0));
PushStyleVar(ImGuiStyleVar_ChildBorderSize, 0.0f);
Begin(title, NULL, window_flags);
PopStyleVar();
if (node->Windows.Size > 0 || node->IsSplitNode())
PopStyleColor();
ImGuiWindow* host_window = g.CurrentWindow;
host_window->DockNodeAsHost = node;
host_window->ChildId = window->GetID(title);
node->HostWindow = host_window;
node->OnlyNodeWithWindows = NULL;
IM_ASSERT(node->IsRootNode());
DockNodeUpdate(node);
End();
}
// Tips: Use with ImGuiDockNodeFlags_PassthruDockspace!
// The limitation with this call is that your window won't have a menu bar.
// Even though we could pass window flags, it would also require the user to be able to call BeginMenuBar() somehow meaning we can't Begin/End in a single function.
// So if you want a menu bar you need to repeat this code manually ourselves. As with advanced other Docking API, we may change this function signature.
ImGuiID ImGui::DockSpaceOverViewport(ImGuiViewport* viewport, ImGuiDockNodeFlags dockspace_flags, const ImGuiWindowClass* window_class)
{
if (viewport == NULL)
viewport = GetMainViewport();
SetNextWindowPos(viewport->Pos);
SetNextWindowSize(viewport->Size);
SetNextWindowViewport(viewport->ID);
ImGuiWindowFlags host_window_flags = 0;
host_window_flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoDocking;
host_window_flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus;
if (dockspace_flags & ImGuiDockNodeFlags_PassthruDockspace)
host_window_flags |= ImGuiWindowFlags_NoBackground;
char label[32];
ImFormatString(label, IM_ARRAYSIZE(label), "DockspaceViewport_%08X", viewport->ID);
PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f));
Begin(label, NULL, host_window_flags);
PopStyleVar(3);
ImGuiID dockspace_id = GetID("Dockspace");
DockSpace(dockspace_id, ImVec2(0.0f, 0.0f), dockspace_flags, window_class);
End();
return dockspace_id;
}
//-----------------------------------------------------------------------------
// Docking: Builder Functions
//-----------------------------------------------------------------------------
// Very early end-user API to manipulate dock nodes.
// It is expected that those functions are all called _before_ the dockspace node submission.
//-----------------------------------------------------------------------------
void ImGui::DockBuilderDockWindow(const char* window_name, ImGuiID node_id)
{
// We don't preserve relative order of multiple docked windows (by clearing DockOrder back to -1)
ImGuiID window_id = ImHashStr(window_name, 0);
if (ImGuiWindow* window = FindWindowByID(window_id))
{
// Apply to created window
SetWindowDock(window, node_id, ImGuiCond_Always);
window->DockOrder = -1;
}
else
{
// Apply to settings
ImGuiWindowSettings* settings = FindWindowSettings(window_id);
if (settings == NULL)
settings = CreateNewWindowSettings(window_name);
settings->DockId = node_id;
settings->DockOrder = -1;
}
}
ImGuiDockNode* ImGui::DockBuilderGetNode(ImGuiID node_id)
{
ImGuiContext* ctx = GImGui;
return DockContextFindNodeByID(ctx, node_id);
}
void ImGui::DockBuilderSetNodePos(ImGuiID node_id, ImVec2 pos)
{
ImGuiContext* ctx = GImGui;
ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
if (node == NULL)
return;
node->Pos = pos;
node->AutorityForPos = ImGuiDataAutority_DockNode;
}
void ImGui::DockBuilderSetNodeSize(ImGuiID node_id, ImVec2 size)
{
ImGuiContext* ctx = GImGui;
ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
if (node == NULL)
return;
node->Size = node->SizeRef = size;
node->AutorityForSize = ImGuiDataAutority_DockNode;
}
// If you create a regular node, both ref_pos/ref_size will position the window.
// If you create a dockspace node: ref_pos won't be used, ref_size is useful on the first frame to...
ImGuiID ImGui::DockBuilderAddNode(ImGuiID id, ImGuiDockNodeFlags flags)
{
ImGuiContext* ctx = GImGui;
ImGuiDockNode* node = NULL;
if (flags & ImGuiDockNodeFlags_Dockspace)
{
DockSpace(id, ImVec2(0, 0), flags | ImGuiDockNodeFlags_KeepAliveOnly);
node = DockContextFindNodeByID(ctx, id);
node->LastFrameAlive = -1;
}
else
{
if (id != 0)
node = DockContextFindNodeByID(ctx, id);
if (!node)
node = DockContextAddNode(ctx, id);
node->LastFrameAlive = ctx->FrameCount;
}
return node->ID;
}
void ImGui::DockBuilderRemoveNode(ImGuiID node_id)
{
ImGuiContext* ctx = GImGui;
ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_id);
if (node == NULL)
return;
DockBuilderRemoveNodeDockedWindows(node_id, true);
DockBuilderRemoveNodeChildNodes(node_id);
if (node->IsCentralNode && node->ParentNode)
node->ParentNode->IsCentralNode = true;
DockContextRemoveNode(ctx, node, true);
}
void ImGui::DockBuilderRemoveNodeChildNodes(ImGuiID root_id)
{
ImGuiContext* ctx = GImGui;
ImGuiDockContext* dc = ctx->DockContext;
ImGuiDockNode* root_node = root_id ? DockContextFindNodeByID(ctx, root_id) : NULL;
if (root_id && root_node == NULL)
return;
bool has_document_root = false;
ImGuiDataAutority backup_root_node_autority_for_pos = root_node ? root_node->AutorityForPos : ImGuiDataAutority_Auto;
ImGuiDataAutority backup_root_node_autority_for_size = root_node ? root_node->AutorityForSize : ImGuiDataAutority_Auto;
// Process active windows
ImVector<ImGuiDockNode*> nodes_to_remove;
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
{
bool want_removal = (root_id == 0) || (node->ID != root_id && DockNodeGetRootNode(node)->ID == root_id);
if (want_removal)
{
if (node->IsCentralNode)
has_document_root = true;
if (root_id != 0)
DockContextQueueNotifyRemovedNode(ctx, node);
if (root_node)
DockNodeMoveWindows(root_node, node);
nodes_to_remove.push_back(node);
}
}
// DockNodeMoveWindows->DockNodeAddWindow will normally set those when reaching two windows (which is only adequate during interactive merge)
// Make sure we don't lose our current pos/size. (FIXME-DOCK: Consider tidying up that code in DockNodeAddWindow instead)
if (root_node)
{
root_node->AutorityForPos = backup_root_node_autority_for_pos;
root_node->AutorityForSize = backup_root_node_autority_for_size;
}
// Apply to settings
for (int settings_n = 0; settings_n < ctx->SettingsWindows.Size; settings_n++)
if (ImGuiID window_settings_dock_id = ctx->SettingsWindows[settings_n].DockId)
for (int n = 0; n < nodes_to_remove.Size; n++)
if (nodes_to_remove[n]->ID == window_settings_dock_id)
{
ctx->SettingsWindows[settings_n].DockId = root_id;
break;
}
// Not really efficient, but easier to destroy a whole hierarchy considering DockContextRemoveNode is attempting to merge nodes
if (nodes_to_remove.Size > 1)
ImQsort(nodes_to_remove.Data, nodes_to_remove.Size, sizeof(ImGuiDockNode*), DockNodeComparerDepthMostFirst);
for (int n = 0; n < nodes_to_remove.Size; n++)
DockContextRemoveNode(ctx, nodes_to_remove[n], false);
if (root_id == 0)
{
dc->Nodes.Clear();
dc->Requests.clear();
}
else if (has_document_root)
{
root_node->IsCentralNode = true;
}
}
void ImGui::DockBuilderRemoveNodeDockedWindows(ImGuiID root_id, bool clear_persistent_docking_references)
{
// Clear references in settings
ImGuiContext* ctx = GImGui;
ImGuiContext& g = *ctx;
if (clear_persistent_docking_references)
{
for (int n = 0; n < g.SettingsWindows.Size; n++)
{
ImGuiWindowSettings* settings = &g.SettingsWindows[n];
bool want_removal = (root_id == 0) || (settings->DockId == root_id);
if (!want_removal && settings->DockId != 0)
if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, settings->DockId))
if (DockNodeGetRootNode(node)->ID == root_id)
want_removal = true;
if (want_removal)
settings->DockId = 0;
}
}
// Clear references in windows
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
bool want_removal = (root_id == 0) || (window->DockNode && DockNodeGetRootNode(window->DockNode)->ID == root_id) || (window->DockNodeAsHost && window->DockNodeAsHost->ID == root_id);
if (want_removal)
{
const ImGuiID backup_dock_id = window->DockId;
DockContextProcessUndockWindow(ctx, window, clear_persistent_docking_references);
if (!clear_persistent_docking_references)
IM_ASSERT(window->DockId == backup_dock_id);
}
}
}
ImGuiID ImGui::DockBuilderSplitNode(ImGuiID id, ImGuiDir split_dir, float size_ratio_for_node_at_dir, ImGuiID* out_id_at_dir, ImGuiID* out_id_other)
{
ImGuiContext* ctx = GImGui;
IM_ASSERT(split_dir != ImGuiDir_None);
ImGuiDockNode* node = DockContextFindNodeByID(ctx, id);
if (node == NULL)
{
IM_ASSERT(node != NULL);
return 0;
}
IM_ASSERT(!node->IsSplitNode()); // Assert if already Split
ImGuiDockRequest req;
req.Type = ImGuiDockRequestType_Split;
req.DockTargetWindow = NULL;
req.DockTargetNode = node;
req.DockPayload = NULL;
req.DockSplitDir = split_dir;
req.DockSplitRatio = ImSaturate((split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? size_ratio_for_node_at_dir : 1.0f - size_ratio_for_node_at_dir);
req.DockSplitOuter = false;
DockContextProcessDock(ctx, &req);
ImGuiID id_at_dir = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 0 : 1]->ID;
ImGuiID id_other = node->ChildNodes[(split_dir == ImGuiDir_Left || split_dir == ImGuiDir_Up) ? 1 : 0]->ID;
if (out_id_at_dir)
*out_id_at_dir = id_at_dir;
if (out_id_other)
*out_id_other = id_other;
return id_at_dir;
}
static ImGuiDockNode* DockBuilderCopyNodeRec(ImGuiDockNode* src_node, ImGuiID dst_node_id_if_known, ImVector<ImGuiID>* out_node_remap_pairs)
{
ImGuiContext* ctx = GImGui;
ImGuiDockNode* dst_node = ImGui::DockContextAddNode(ctx, dst_node_id_if_known);
dst_node->Flags = src_node->Flags;
dst_node->Pos = src_node->Pos;
dst_node->Size = src_node->Size;
dst_node->SizeRef = src_node->SizeRef;
dst_node->SplitAxis = src_node->SplitAxis;
dst_node->IsCentralNode = src_node->IsCentralNode;
out_node_remap_pairs->push_back(src_node->ID);
out_node_remap_pairs->push_back(dst_node->ID);
for (int child_n = 0; child_n < IM_ARRAYSIZE(src_node->ChildNodes); child_n++)
if (src_node->ChildNodes[child_n])
{
dst_node->ChildNodes[child_n] = DockBuilderCopyNodeRec(src_node->ChildNodes[child_n], 0, out_node_remap_pairs);
dst_node->ChildNodes[child_n]->ParentNode = dst_node;
}
//IMGUI_DEBUG_LOG("Fork node %08X -> %08X (%d childs)\n", src_node->ID, dst_node->ID, dst_node->IsSplitNode() ? 2 : 0);
return dst_node;
}
void ImGui::DockBuilderCopyNode(ImGuiID src_node_id, ImGuiID dst_node_id, ImVector<ImGuiID>* out_node_remap_pairs)
{
ImGuiContext* ctx = GImGui;
IM_ASSERT(src_node_id != 0);
IM_ASSERT(dst_node_id != 0);
IM_ASSERT(out_node_remap_pairs != NULL);
ImGuiDockNode* src_node = DockContextFindNodeByID(ctx, src_node_id);
IM_ASSERT(src_node != NULL);
out_node_remap_pairs->clear();
DockBuilderRemoveNode(dst_node_id);
DockBuilderCopyNodeRec(src_node, dst_node_id, out_node_remap_pairs);
IM_ASSERT((out_node_remap_pairs->Size % 2) == 0);
}
void ImGui::DockBuilderCopyWindowSettings(const char* src_name, const char* dst_name)
{
ImGuiWindow* src_window = FindWindowByName(src_name);
if (src_window == NULL)
return;
if (ImGuiWindow* dst_window = FindWindowByName(dst_name))
{
dst_window->Pos = src_window->Pos;
dst_window->Size = src_window->Size;
dst_window->SizeFull = src_window->SizeFull;
dst_window->Collapsed = src_window->Collapsed;
}
else if (ImGuiWindowSettings* dst_settings = FindOrCreateWindowSettings(dst_name))
{
if (src_window->ViewportId != 0 && src_window->ViewportId != IMGUI_VIEWPORT_DEFAULT_ID)
{
dst_settings->ViewportPos = src_window->Pos;
dst_settings->ViewportId = src_window->ViewportId;
dst_settings->Pos = ImVec2(0.0f, 0.0f);
}
else
{
dst_settings->Pos = src_window->Pos;
}
dst_settings->Size = src_window->SizeFull;
dst_settings->Collapsed = src_window->Collapsed;
}
}
// FIXME: Will probably want to change this signature, in particular how the window remapping pairs are passed.
void ImGui::DockBuilderCopyDockspace(ImGuiID src_dockspace_id, ImGuiID dst_dockspace_id, ImVector<const char*>* in_window_remap_pairs)
{
IM_ASSERT(src_dockspace_id != 0);
IM_ASSERT(dst_dockspace_id != 0);
IM_ASSERT(in_window_remap_pairs != NULL);
IM_ASSERT((in_window_remap_pairs->Size % 2) == 0);
// Duplicate entire dock
// FIXME: When overwriting dst_dockspace_id, windows that aren't part of our dockspace window class but that are docked in a same node will be split apart,
// whereas we could attempt to at least keep them together in a new, same floating node.
ImVector<ImGuiID> node_remap_pairs;
DockBuilderCopyNode(src_dockspace_id, dst_dockspace_id, &node_remap_pairs);
// Attempt to transition all the upcoming windows associated to dst_dockspace_id into the newly created hierarchy of dock nodes
// (The windows associated to src_dockspace_id are staying in place)
ImVector<ImGuiID> src_windows;
for (int remap_window_n = 0; remap_window_n < in_window_remap_pairs->Size; remap_window_n += 2)
{
const char* src_window_name = (*in_window_remap_pairs)[remap_window_n];
const char* dst_window_name = (*in_window_remap_pairs)[remap_window_n + 1];
ImGuiID src_window_id = ImHashStr(src_window_name, 0);
src_windows.push_back(src_window_id);
// Search in the remapping tables
ImGuiID src_dock_id = 0;
if (ImGuiWindow* src_window = FindWindowByID(src_window_id))
src_dock_id = src_window->DockId;
else if (ImGuiWindowSettings* src_window_settings = FindWindowSettings(src_window_id))
src_dock_id = src_window_settings->DockId;
ImGuiID dst_dock_id = 0;
for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
if (node_remap_pairs[dock_remap_n] == src_dock_id)
{
dst_dock_id = node_remap_pairs[dock_remap_n + 1];
//node_remap_pairs[dock_remap_n] = node_remap_pairs[dock_remap_n + 1] = 0; // Clear
break;
}
if (dst_dock_id != 0)
{
// Docked windows gets redocked into the new node hierarchy.
//IMGUI_DEBUG_LOG("Remap window '%s' %08X -> %08X\n", dst_window_name, src_dock_id, dst_dock_id);
DockBuilderDockWindow(dst_window_name, dst_dock_id);
}
else
{
// Floating windows gets their settings transferred (regardless of whether the new window already exist or not)
// When this is leading to a Copy and not a Move, we would get two overlapping floating windows. Could we possibly dock them together?
DockBuilderCopyWindowSettings(src_window_name, dst_window_name);
}
}
// Anything else in the source nodes of 'node_remap_pairs' are windows that were docked in src_dockspace_id but are not owned by it (unaffiliated windows, e.g. "ImGui Demo")
// Find those windows and move to them to the cloned dock node. This may be optional?
for (int dock_remap_n = 0; dock_remap_n < node_remap_pairs.Size; dock_remap_n += 2)
if (ImGuiID src_dock_id = node_remap_pairs[dock_remap_n])
{
ImGuiID dst_dock_id = node_remap_pairs[dock_remap_n + 1];
ImGuiDockNode* node = DockBuilderGetNode(src_dock_id);
for (int window_n = 0; window_n < node->Windows.Size; window_n++)
{
ImGuiWindow* window = node->Windows[window_n];
if (src_windows.contains(window->ID))
continue;
// Docked windows gets redocked into the new node hierarchy.
//IMGUI_DEBUG_LOG("Remap window '%s' %08X -> %08X\n", window->Name, src_dock_id, dst_dock_id);
DockBuilderDockWindow(window->Name, dst_dock_id);
}
}
}
void ImGui::DockBuilderFinish(ImGuiID root_id)
{
ImGuiContext* ctx = GImGui;
//DockContextRebuild(ctx);
DockContextBuildAddWindowsToNodes(ctx, root_id);
}
//-----------------------------------------------------------------------------
// Docking: Begin/End Functions (called from Begin/End)
//-----------------------------------------------------------------------------
void ImGui::BeginDocked(ImGuiWindow* window, bool* p_open)
{
ImGuiContext* ctx = GImGui;
ImGuiContext& g = *ctx;
const bool auto_dock_node = (g.IO.ConfigDockingTabBarOnSingleWindows) && !(window->Flags & (ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoDocking));
if (auto_dock_node)
{
if (window->DockId == 0)
{
IM_ASSERT(window->DockNode == NULL);
window->DockId = DockContextGenNodeID(ctx);
}
}
else
{
// Calling SetNextWindowPos() undock windows by default (by setting PosUndock)
bool want_undock = false;
want_undock |= (window->Flags & ImGuiWindowFlags_NoDocking) != 0;
want_undock |= (g.NextWindowData.PosCond && (window->SetWindowPosAllowFlags & g.NextWindowData.PosCond) && g.NextWindowData.PosUndock);
g.NextWindowData.PosUndock = false;
if (want_undock)
{
DockContextProcessUndockWindow(ctx, window);
return;
}
}
// Bind to our dock node
ImGuiDockNode* node = window->DockNode;
if (node != NULL)
IM_ASSERT(window->DockId == node->ID);
if (window->DockId != 0 && node == NULL)
{
node = DockContextFindNodeByID(ctx, window->DockId);
// We should not be docking into a split node (SetWindowDock should avoid this)
if (node && node->IsSplitNode())
{
DockContextProcessUndockWindow(ctx, window);
return;
}
// Create node
if (node == NULL)
{
node = DockContextAddNode(ctx, window->DockId);
if (auto_dock_node)
node->LastFrameAlive = g.FrameCount;
}
DockNodeAddWindow(node, window, true);
IM_ASSERT(node == window->DockNode);
// Fix an edge case with auto-resizing windows: if they are created on the same frame they are creating their dock node,
// we don't want their initial zero-size to spread to the DockNode. We preserve their size.
SetNextWindowPos(window->Pos);
SetNextWindowSize(window->SizeFull);
g.NextWindowData.PosUndock = false;
}
// Undock if the ImGuiDockNodeFlags_NoDockingInCentralNode got set
if (node->IsCentralNode && (node->Flags & ImGuiDockNodeFlags_NoDockingInCentralNode))
{
DockContextProcessUndockWindow(ctx, window);
return;
}
// Undock if our dockspace node disappeared
// Note how we are testing for LastFrameAlive and NOT LastFrameActive. A DockSpace node can be maintained alive while being inactive with ImGuiDockNodeFlags_KeepAliveOnly.
if (node->LastFrameAlive < g.FrameCount)
{
// If the window has been orphaned, transition the docknode to an implicit node processed in DockContextUpdateDocking()
ImGuiDockNode* root_node = DockNodeGetRootNode(node);
if (root_node->LastFrameAlive < g.FrameCount)
{
DockContextProcessUndockWindow(ctx, window);
}
else
{
window->DockIsActive = true;
window->DockTabIsVisible = false;
}
return;
}
// Undock if we are submitted earlier than the host window
if (node->HostWindow && window->BeginOrderWithinContext < node->HostWindow->BeginOrderWithinContext)
{
DockContextProcessUndockWindow(ctx, window);
return;
}
// FIXME-DOCK: replace ->HostWindow NULL compare with something more explicit (~was initially intended as a first frame test)
if (node->HostWindow == NULL)
{
window->DockTabIsVisible = false;
return;
}
IM_ASSERT(node->HostWindow);
IM_ASSERT(node->IsLeafNode());
// Position window
SetNextWindowPos(node->Pos);
SetNextWindowSize(node->Size);
g.NextWindowData.PosUndock = false; // Cancel implicit undocking of SetNextWindowPos()
window->DockIsActive = true;
window->DockTabIsVisible = false;
if (node->Flags & ImGuiDockNodeFlags_KeepAliveOnly)
return;
// When the window is selected we mark it as visible.
if (node->TabBar && node->TabBar->VisibleTabId == window->ID)
window->DockTabIsVisible = true;
// When we are about to select this tab (which will only be visible on the _next frame_), flag it with a non-zero HiddenFramesForResize.
// This will have the important effect of actually returning true in Begin() and not setting SkipItems, allowing an earlier submission of the window contents.
// This is analogous to regular windows being hidden from one frame. It is especially important as nested TabBars would otherwise generate flicker in the form
// of one empty frame.
// Note that we set HiddenFramesForResize=2 because BeginDocked() is called just before Begin() has a chance to decrement the value. Effectively it'll be a 1 frame thing.
if (!window->DockTabIsVisible && node->TabBar && node->TabBar->NextSelectedTabId == window->ID)
window->HiddenFramesForResize = 2;
// Update window flag
IM_ASSERT((window->Flags & ImGuiWindowFlags_ChildWindow) == 0);
window->Flags |= ImGuiWindowFlags_ChildWindow | ImGuiWindowFlags_AlwaysUseWindowPadding | ImGuiWindowFlags_NoResize;
if (node->IsHiddenTabBar)
window->Flags |= ImGuiWindowFlags_NoTitleBar;
else
window->Flags &= ~ImGuiWindowFlags_NoTitleBar; // Clear the NoTitleBar flag in case the user set it: confusingly enough we need a title bar height so we are correctly offset, but it won't be displayed!
// Save new dock order only if the tab bar is active
if (node->TabBar)
window->DockOrder = (short)DockNodeGetTabOrder(window);
if ((node->WantCloseAll || node->WantCloseTabID == window->ID) && p_open != NULL)
*p_open = false;
// Update ChildId to allow returning from Child to Parent with Escape
ImGuiWindow* parent_window = window->DockNode->HostWindow;
window->ChildId = parent_window->GetID(window->Name);
}
void ImGui::BeginAsDockableDragDropSource(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.ActiveId == window->MoveId);
window->DC.LastItemId = window->MoveId;
window = window->RootWindow;
IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
bool is_drag_docking = (g.IO.ConfigDockingWithShift) || ImRect(0, 0, window->SizeFull.x, GetFrameHeight()).Contains(g.ActiveIdClickOffset);
if (is_drag_docking && BeginDragDropSource(ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers | ImGuiDragDropFlags_SourceAutoExpirePayload))
{
SetDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, &window, sizeof(window));
EndDragDropSource();
}
}
void ImGui::BeginAsDockableDragDropTarget(ImGuiWindow* window)
{
ImGuiContext* ctx = GImGui;
ImGuiContext& g = *ctx;
IM_ASSERT((window->Flags & ImGuiWindowFlags_NoDocking) == 0);
if (!g.DragDropActive)
return;
if (!BeginDragDropTargetCustom(window->Rect(), window->ID))
return;
// Peek into the payload before calling AcceptDragDropPayload() so we can handle overlapping dock nodes with filtering
// (this is a little unusual pattern, normally most code would call AcceptDragDropPayload directly)
const ImGuiPayload* payload = &g.DragDropPayload;
if (!payload->IsDataType(IMGUI_PAYLOAD_TYPE_WINDOW) || !DockNodeIsDropAllowed(window, *(ImGuiWindow**)payload->Data))
{
EndDragDropTarget();
return;
}
ImGuiWindow* payload_window = *(ImGuiWindow**)payload->Data;
if (AcceptDragDropPayload(IMGUI_PAYLOAD_TYPE_WINDOW, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect))
{
bool allow_null_target_node = false;
ImGuiDockNode* target_node = NULL;
if (window->DockNodeAsHost)
target_node = DockNodeTreeFindNodeByPos(window->DockNodeAsHost, g.IO.MousePos);
else if (window->DockNode) // && window->DockIsActive)
target_node = window->DockNode;
else
allow_null_target_node = true; // Dock into a regular window
const ImRect explicit_target_rect = (target_node && target_node->TabBar && !target_node->IsHiddenTabBar) ? target_node->TabBar->BarRect : ImRect(window->Pos, window->Pos + ImVec2(window->Size.x, GetFrameHeight()));
const bool is_explicit_target = g.IO.ConfigDockingWithShift || IsMouseHoveringRect(explicit_target_rect.Min, explicit_target_rect.Max);
// Preview docking request and find out split direction/ratio
//const bool do_preview = true; // Ignore testing for payload->IsPreview() which removes one frame of delay, but breaks overlapping drop targets within the same window.
const bool do_preview = payload->IsPreview() || payload->IsDelivery();
if (do_preview && (target_node != NULL || allow_null_target_node))
{
ImGuiDockPreviewData split_inner, split_outer;
ImGuiDockPreviewData* split_data = &split_inner;
if (target_node && (target_node->ParentNode || target_node->IsCentralNode))
if (ImGuiDockNode* root_node = DockNodeGetRootNode(target_node))
if (DockNodePreviewDockCalc(window, root_node, payload_window, &split_outer, is_explicit_target, true))
split_data = &split_outer;
DockNodePreviewDockCalc(window, target_node, payload_window, &split_inner, is_explicit_target, false);
if (split_data == &split_outer)
split_inner.IsDropAllowed = false;
// Draw inner then outer, so that previewed tab (in inner data) will be behind the outer drop boxes
DockNodePreviewDockRender(window, target_node, payload_window, &split_inner);
DockNodePreviewDockRender(window, target_node, payload_window, &split_outer);
// Queue docking request
if (split_data->IsDropAllowed && payload->IsDelivery())
DockContextQueueDock(ctx, window, split_data->SplitNode, payload_window, split_data->SplitDir, split_data->SplitRatio, split_data == &split_outer);
}
}
EndDragDropTarget();
}
//-----------------------------------------------------------------------------
// Docking: Settings
//-----------------------------------------------------------------------------
static void ImGui::DockSettingsRenameNodeReferences(ImGuiID old_node_id, ImGuiID new_node_id)
{
ImGuiContext& g = *GImGui;
for (int window_n = 0; window_n < g.Windows.Size; window_n++)
{
ImGuiWindow* window = g.Windows[window_n];
if (window->DockId == old_node_id && window->DockNode == NULL)
window->DockId = new_node_id;
}
for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) // FIXME-OPT: We could remove this loop by storing the index in the map
{
ImGuiWindowSettings* window_settings = &g.SettingsWindows[settings_n];
if (window_settings->DockId == old_node_id)
window_settings->DockId = new_node_id;
}
}
// Remove references stored in ImGuiWindowSettings to the given ImGuiDockNodeSettings
static void ImGui::DockSettingsRemoveNodeReferences(ImGuiID* node_ids, int node_ids_count)
{
ImGuiContext& g = *GImGui;
int found = 0;
for (int settings_n = 0; settings_n < g.SettingsWindows.Size; settings_n++) // FIXME-OPT: We could remove this loop by storing the index in the map
{
ImGuiWindowSettings* window_settings = &g.SettingsWindows[settings_n];
for (int node_n = 0; node_n < node_ids_count; node_n++)
if (window_settings->DockId == node_ids[node_n])
{
window_settings->DockId = 0;
window_settings->DockOrder = -1;
if (++found < node_ids_count)
break;
return;
}
}
}
static ImGuiDockNodeSettings* ImGui::DockSettingsFindNodeSettings(ImGuiContext* ctx, ImGuiID id)
{
// FIXME-OPT
ImGuiDockContext* dc = ctx->DockContext;
for (int n = 0; n < dc->SettingsNodes.Size; n++)
if (dc->SettingsNodes[n].ID == id)
return &dc->SettingsNodes[n];
return NULL;
}
static void* ImGui::DockSettingsHandler_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
if (strcmp(name, "Data") != 0)
return NULL;
return (void*)1;
}
static void ImGui::DockSettingsHandler_ReadLine(ImGuiContext* ctx, ImGuiSettingsHandler*, void*, const char* line)
{
char c = 0;
int x = 0, y = 0;
int r = 0;
// Parsing, e.g.
// " DockNode ID=0x00000001 Pos=383,193 Size=201,322 Split=Y,0.506 "
// " DockNode ID=0x00000002 Parent=0x00000001 "
ImGuiDockNodeSettings node;
line = ImStrSkipBlank(line);
if (strncmp(line, "DockNode", 8) == 0) { line = ImStrSkipBlank(line + strlen("DockNode")); }
else if (strncmp(line, "DockSpace", 9) == 0) { line = ImStrSkipBlank(line + strlen("DockSpace")); node.IsDockSpace = true; }
else return;
if (sscanf(line, "ID=0x%08X%n", &node.ID, &r) == 1) { line += r; } else return;
if (sscanf(line, " Parent=0x%08X%n", &node.ParentID, &r) == 1) { line += r; if (node.ParentID == 0) return; }
if (node.ParentID == 0)
{
if (sscanf(line, " Pos=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Pos = ImVec2ih((short)x, (short)y); } else return;
if (sscanf(line, " Size=%i,%i%n", &x, &y, &r) == 2) { line += r; node.Size = ImVec2ih((short)x, (short)y); } else return;
}
else
{
if (sscanf(line, " SizeRef=%i,%i%n", &x, &y, &r) == 2) { line += r; node.SizeRef = ImVec2ih((short)x, (short)y); }
}
if (sscanf(line, " Split=%c%n", &c, &r) == 1) { line += r; if (c == 'X') node.SplitAxis = ImGuiAxis_X; else if (c == 'Y') node.SplitAxis = ImGuiAxis_Y; }
if (sscanf(line, " CentralNode=%d%n", &x, &r) == 1) { line += r; node.IsCentralNode = (x != 0); }
if (sscanf(line, " HiddenTabBar=%d%n", &x, &r) == 1) { line += r; node.IsHiddenTabBar = (x != 0); }
if (sscanf(line, " SelectedTab=0x%08X%n", &node.SelectedTabID,&r) == 1) { line += r; }
ImGuiDockContext* dc = ctx->DockContext;
if (node.ParentID != 0)
if (ImGuiDockNodeSettings* parent_settings = DockSettingsFindNodeSettings(ctx, node.ParentID))
node.Depth = parent_settings->Depth + 1;
dc->SettingsNodes.push_back(node);
}
static void DockSettingsHandler_DockNodeToSettings(ImGuiDockContext* dc, ImGuiDockNode* node, int depth)
{
ImGuiDockNodeSettings node_settings;
IM_ASSERT(depth < (1 << (sizeof(node_settings.Depth) << 3)));
node_settings.ID = node->ID;
node_settings.ParentID = node->ParentNode ? node->ParentNode->ID : 0;
node_settings.SelectedTabID = node->SelectedTabID;
node_settings.SplitAxis = node->IsSplitNode() ? (char)node->SplitAxis : ImGuiAxis_None;
node_settings.Depth = (char)depth;
node_settings.IsDockSpace = (char)node->IsDockSpace();
node_settings.IsCentralNode = (char)node->IsCentralNode;
node_settings.IsHiddenTabBar = (char)node->IsHiddenTabBar;
node_settings.Pos = ImVec2ih((short)node->Pos.x, (short)node->Pos.y);
node_settings.Size = ImVec2ih((short)node->Size.x, (short)node->Size.y);
node_settings.SizeRef = ImVec2ih((short)node->SizeRef.x, (short)node->SizeRef.y);
dc->SettingsNodes.push_back(node_settings);
if (node->ChildNodes[0])
DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[0], depth + 1);
if (node->ChildNodes[1])
DockSettingsHandler_DockNodeToSettings(dc, node->ChildNodes[1], depth + 1);
}
static void ImGui::DockSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = g.DockContext;
if (!(g.IO.ConfigFlags & ImGuiConfigFlags_DockingEnable))
return;
// Gather settings data
// (unlike our windows settings, because nodes are always built we can do a full rewrite of the SettingsNode buffer)
dc->SettingsNodes.resize(0);
dc->SettingsNodes.reserve(dc->Nodes.Data.Size);
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
if (node->IsRootNode())
DockSettingsHandler_DockNodeToSettings(dc, node, 0);
int max_depth = 0;
for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
max_depth = ImMax((int)dc->SettingsNodes[node_n].Depth, max_depth);
// Write to text buffer
buf->appendf("[%s][Data]\n", handler->TypeName);
for (int node_n = 0; node_n < dc->SettingsNodes.Size; node_n++)
{
const int line_start_pos = buf->size(); (void)line_start_pos;
const ImGuiDockNodeSettings* node_settings = &dc->SettingsNodes[node_n];
buf->appendf("%*s%s%*s", node_settings->Depth * 2, "", node_settings->IsDockSpace ? "DockSpace" : "DockNode ", (max_depth - node_settings->Depth) * 2, ""); // Text align nodes to facilitate looking at .ini file
buf->appendf(" ID=0x%08X", node_settings->ID);
if (node_settings->ParentID)
buf->appendf(" Parent=0x%08X SizeRef=%d,%d", node_settings->ParentID, node_settings->SizeRef.x, node_settings->SizeRef.y);
else
buf->appendf(" Pos=%d,%d Size=%d,%d", node_settings->Pos.x, node_settings->Pos.y, node_settings->Size.x, node_settings->Size.y);
if (node_settings->SplitAxis != ImGuiAxis_None)
buf->appendf(" Split=%c", (node_settings->SplitAxis == ImGuiAxis_X) ? 'X' : 'Y');
if (node_settings->IsCentralNode)
buf->appendf(" CentralNode=1");
if (node_settings->IsHiddenTabBar)
buf->appendf(" HiddenTabBar=1");
if (node_settings->SelectedTabID)
buf->appendf(" SelectedTab=0x%08X", node_settings->SelectedTabID);
#if IMGUI_DEBUG_DOCKING_INI
// [DEBUG] Include comments in the .ini file to ease debugging
if (ImGuiDockNode* node = DockContextFindNodeByID(ctx, node_settings->ID))
{
buf->appendf("%*s", ImMax(2, (line_start_pos + 92) - buf->size()), ""); // Align everything
if (node->IsDockSpace && node->HostWindow && node->HostWindow->ParentWindow)
buf->appendf(" ; in '%s'", node->HostWindow->ParentWindow->Name);
int contains_window = 0;
for (int window_n = 0; window_n < ctx->SettingsWindows.Size; window_n++)
if (ctx->SettingsWindows[window_n].DockId == node_settings->ID)
{
if (contains_window++ == 0)
buf->appendf(" ; contains ");
buf->appendf("'%s' ", ctx->SettingsWindows[window_n].Name);
}
}
#endif
buf->appendf("\n");
}
buf->appendf("\n");
}
//-----------------------------------------------------------------------------
// [SECTION] LOGGING/CAPTURING
//-----------------------------------------------------------------------------
// All text output from the interface can be captured into tty/file/clipboard.
// By default, tree nodes are automatically opened during logging.
//-----------------------------------------------------------------------------
// Pass text data straight to log (without being displayed)
void ImGui::LogText(const char* fmt, ...)
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
va_list args;
va_start(args, fmt);
if (g.LogFile)
vfprintf(g.LogFile, fmt, args);
else
g.LogClipboard.appendfv(fmt, args);
va_end(args);
}
// Internal version that takes a position to decide on newline placement and pad items according to their depth.
// We split text into individual lines to add current tree level padding
void ImGui::LogRenderedText(const ImVec2* ref_pos, const char* text, const char* text_end)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
if (!text_end)
text_end = FindRenderedTextEnd(text, text_end);
const bool log_new_line = ref_pos && (ref_pos->y > window->DC.LogLinePosY + 1);
if (ref_pos)
window->DC.LogLinePosY = ref_pos->y;
const char* text_remaining = text;
if (g.LogStartDepth > window->DC.TreeDepth) // Re-adjust padding if we have popped out of our starting depth
g.LogStartDepth = window->DC.TreeDepth;
const int tree_depth = (window->DC.TreeDepth - g.LogStartDepth);
for (;;)
{
// Split the string. Each new line (after a '\n') is followed by spacing corresponding to the current depth of our log entry.
const char* line_start = text_remaining;
const char* line_end = ImStreolRange(line_start, text_end);
const bool is_first_line = (line_start == text);
const bool is_last_line = (line_end == text_end);
if (!is_last_line || (line_start != line_end))
{
const int char_count = (int)(line_end - line_start);
if (log_new_line || !is_first_line)
LogText(IM_NEWLINE "%*s%.*s", tree_depth*4, "", char_count, line_start);
else
LogText(" %.*s", char_count, line_start);
}
if (is_last_line)
break;
text_remaining = line_end + 1;
}
}
// Start logging ImGui output to TTY
void ImGui::LogToTTY(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogFile == NULL);
g.LogFile = stdout;
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to given file
void ImGui::LogToFile(int max_depth, const char* filename)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
if (!filename)
{
filename = g.IO.LogFilename;
if (!filename)
return;
}
IM_ASSERT(g.LogFile == NULL);
g.LogFile = ImFileOpen(filename, "ab");
if (g.LogFile == NULL)
{
IM_ASSERT(0);
return;
}
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
// Start logging ImGui output to clipboard
void ImGui::LogToClipboard(int max_depth)
{
ImGuiContext& g = *GImGui;
if (g.LogEnabled)
return;
ImGuiWindow* window = g.CurrentWindow;
IM_ASSERT(g.LogFile == NULL);
g.LogFile = NULL;
g.LogEnabled = true;
g.LogStartDepth = window->DC.TreeDepth;
if (max_depth >= 0)
g.LogAutoExpandMaxDepth = max_depth;
}
void ImGui::LogFinish()
{
ImGuiContext& g = *GImGui;
if (!g.LogEnabled)
return;
LogText(IM_NEWLINE);
if (g.LogFile != NULL)
{
if (g.LogFile == stdout)
fflush(g.LogFile);
else
fclose(g.LogFile);
g.LogFile = NULL;
}
if (g.LogClipboard.size() > 1)
{
SetClipboardText(g.LogClipboard.begin());
g.LogClipboard.clear();
}
g.LogEnabled = false;
}
// Helper to display logging buttons
void ImGui::LogButtons()
{
ImGuiContext& g = *GImGui;
PushID("LogButtons");
const bool log_to_tty = Button("Log To TTY"); SameLine();
const bool log_to_file = Button("Log To File"); SameLine();
const bool log_to_clipboard = Button("Log To Clipboard"); SameLine();
PushItemWidth(80.0f);
PushAllowKeyboardFocus(false);
SliderInt("Depth", &g.LogAutoExpandMaxDepth, 0, 9, NULL);
PopAllowKeyboardFocus();
PopItemWidth();
PopID();
// Start logging at the end of the function so that the buttons don't appear in the log
if (log_to_tty)
LogToTTY(g.LogAutoExpandMaxDepth);
if (log_to_file)
LogToFile(g.LogAutoExpandMaxDepth, g.IO.LogFilename);
if (log_to_clipboard)
LogToClipboard(g.LogAutoExpandMaxDepth);
}
//-----------------------------------------------------------------------------
// [SECTION] SETTINGS
//-----------------------------------------------------------------------------
void ImGui::MarkIniSettingsDirty()
{
ImGuiContext& g = *GImGui;
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
void ImGui::MarkIniSettingsDirty(ImGuiWindow* window)
{
ImGuiContext& g = *GImGui;
if (!(window->Flags & ImGuiWindowFlags_NoSavedSettings))
if (g.SettingsDirtyTimer <= 0.0f)
g.SettingsDirtyTimer = g.IO.IniSavingRate;
}
ImGuiWindowSettings* ImGui::CreateNewWindowSettings(const char* name)
{
ImGuiContext& g = *GImGui;
g.SettingsWindows.push_back(ImGuiWindowSettings());
ImGuiWindowSettings* settings = &g.SettingsWindows.back();
settings->Name = ImStrdup(name);
settings->ID = ImHashStr(name, 0);
return settings;
}
ImGuiWindowSettings* ImGui::FindWindowSettings(ImGuiID id)
{
ImGuiContext& g = *GImGui;
for (int i = 0; i != g.SettingsWindows.Size; i++)
if (g.SettingsWindows[i].ID == id)
return &g.SettingsWindows[i];
return NULL;
}
ImGuiWindowSettings* ImGui::FindOrCreateWindowSettings(const char* name)
{
if (ImGuiWindowSettings* settings = FindWindowSettings(ImHashStr(name, 0)))
return settings;
return CreateNewWindowSettings(name);
}
void ImGui::LoadIniSettingsFromDisk(const char* ini_filename)
{
size_t file_data_size = 0;
char* file_data = (char*)ImFileLoadToMemory(ini_filename, "rb", &file_data_size);
if (!file_data)
return;
LoadIniSettingsFromMemory(file_data, (size_t)file_data_size);
ImGui::MemFree(file_data);
}
ImGuiSettingsHandler* ImGui::FindSettingsHandler(const char* type_name)
{
ImGuiContext& g = *GImGui;
const ImGuiID type_hash = ImHashStr(type_name, 0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
if (g.SettingsHandlers[handler_n].TypeHash == type_hash)
return &g.SettingsHandlers[handler_n];
return NULL;
}
// Zero-tolerance, no error reporting, cheap .ini parsing
void ImGui::LoadIniSettingsFromMemory(const char* ini_data, size_t ini_size)
{
ImGuiContext& g = *GImGui;
IM_ASSERT(g.Initialized);
IM_ASSERT(g.SettingsLoaded == false && g.FrameCount == 0);
// For user convenience, we allow passing a non zero-terminated string (hence the ini_size parameter).
// For our convenience and to make the code simpler, we'll also write zero-terminators within the buffer. So let's create a writable copy..
if (ini_size == 0)
ini_size = strlen(ini_data);
char* buf = (char*)ImGui::MemAlloc(ini_size + 1);
char* buf_end = buf + ini_size;
memcpy(buf, ini_data, ini_size);
buf[ini_size] = 0;
void* entry_data = NULL;
ImGuiSettingsHandler* entry_handler = NULL;
char* line_end = NULL;
for (char* line = buf; line < buf_end; line = line_end + 1)
{
// Skip new lines markers, then find end of the line
while (*line == '\n' || *line == '\r')
line++;
line_end = line;
while (line_end < buf_end && *line_end != '\n' && *line_end != '\r')
line_end++;
line_end[0] = 0;
if (line[0] == ';')
continue;
if (line[0] == '[' && line_end > line && line_end[-1] == ']')
{
// Parse "[Type][Name]". Note that 'Name' can itself contains [] characters, which is acceptable with the current format and parsing code.
line_end[-1] = 0;
const char* name_end = line_end - 1;
const char* type_start = line + 1;
char* type_end = (char*)(intptr_t)ImStrchrRange(type_start, name_end, ']');
const char* name_start = type_end ? ImStrchrRange(type_end + 1, name_end, '[') : NULL;
if (!type_end || !name_start)
{
name_start = type_start; // Import legacy entries that have no type
type_start = "Window";
}
else
{
*type_end = 0; // Overwrite first ']'
name_start++; // Skip second '['
}
entry_handler = FindSettingsHandler(type_start);
entry_data = entry_handler ? entry_handler->ReadOpenFn(&g, entry_handler, name_start) : NULL;
}
else if (entry_handler != NULL && entry_data != NULL)
{
// Let type handler parse the line
entry_handler->ReadLineFn(&g, entry_handler, entry_data, line);
}
}
ImGui::MemFree(buf);
g.SettingsLoaded = true;
DockContextOnLoadSettings(&g);
}
void ImGui::SaveIniSettingsToDisk(const char* ini_filename)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
if (!ini_filename)
return;
size_t ini_data_size = 0;
const char* ini_data = SaveIniSettingsToMemory(&ini_data_size);
FILE* f = ImFileOpen(ini_filename, "wt");
if (!f)
return;
fwrite(ini_data, sizeof(char), ini_data_size, f);
fclose(f);
}
// Call registered handlers (e.g. SettingsHandlerWindow_WriteAll() + custom handlers) to write their stuff into a text buffer
const char* ImGui::SaveIniSettingsToMemory(size_t* out_size)
{
ImGuiContext& g = *GImGui;
g.SettingsDirtyTimer = 0.0f;
g.SettingsIniData.Buf.resize(0);
g.SettingsIniData.Buf.push_back(0);
for (int handler_n = 0; handler_n < g.SettingsHandlers.Size; handler_n++)
{
ImGuiSettingsHandler* handler = &g.SettingsHandlers[handler_n];
handler->WriteAllFn(&g, handler, &g.SettingsIniData);
}
if (out_size)
*out_size = (size_t)g.SettingsIniData.size();
return g.SettingsIniData.c_str();
}
static void* SettingsHandlerWindow_ReadOpen(ImGuiContext*, ImGuiSettingsHandler*, const char* name)
{
ImGuiWindowSettings* settings = ImGui::FindWindowSettings(ImHashStr(name, 0));
if (!settings)
settings = ImGui::CreateNewWindowSettings(name);
return (void*)settings;
}
static void SettingsHandlerWindow_ReadLine(ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line)
{
ImGuiWindowSettings* settings = (ImGuiWindowSettings*)entry;
float x, y;
int i;
ImU32 u1;
if (sscanf(line, "Pos=%f,%f", &x, &y) == 2) { settings->Pos = ImVec2(x, y); }
else if (sscanf(line, "Size=%f,%f", &x, &y) == 2) { settings->Size = ImMax(ImVec2(x, y), GImGui->Style.WindowMinSize); }
else if (sscanf(line, "ViewportId=0x%08X", &u1) == 1) { settings->ViewportId = u1; }
else if (sscanf(line, "ViewportPos=%f,%f", &x, &y) == 2) { settings->ViewportPos = ImVec2(x, y); }
else if (sscanf(line, "Collapsed=%d", &i) == 1) { settings->Collapsed = (i != 0); }
else if (sscanf(line, "DockId=0x%X,%d", &u1, &i) == 2) { settings->DockId = u1; settings->DockOrder = (short)i; }
else if (sscanf(line, "DockId=0x%X", &u1) == 1) { settings->DockId = u1; settings->DockOrder = -1; }
else if (sscanf(line, "ClassId=0x%X", &u1) == 1) { settings->ClassId = u1; }
}
static void SettingsHandlerWindow_WriteAll(ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf)
{
// Gather data from windows that were active during this session
// (if a window wasn't opened in this session we preserve its settings)
ImGuiContext& g = *imgui_ctx;
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* window = g.Windows[i];
if (window->Flags & ImGuiWindowFlags_NoSavedSettings)
continue;
ImGuiWindowSettings* settings = (window->SettingsIdx != -1) ? &g.SettingsWindows[window->SettingsIdx] : ImGui::FindWindowSettings(window->ID);
if (!settings)
{
settings = ImGui::CreateNewWindowSettings(window->Name);
window->SettingsIdx = g.SettingsWindows.index_from_ptr(settings);
}
IM_ASSERT(settings->ID == window->ID);
settings->Pos = window->Pos - window->ViewportPos;
settings->Size = window->SizeFull;
settings->ViewportId = window->ViewportId;
settings->ViewportPos = window->ViewportPos;
IM_ASSERT(window->DockNode == NULL || window->DockNode->ID == window->DockId);
settings->DockId = window->DockId;
settings->ClassId = window->WindowClass.ClassId;
settings->DockOrder = window->DockOrder;
settings->Collapsed = window->Collapsed;
}
// Write to text buffer
buf->reserve(buf->size() + g.SettingsWindows.Size * 96); // ballpark reserve
for (int i = 0; i != g.SettingsWindows.Size; i++)
{
const ImGuiWindowSettings* settings = &g.SettingsWindows[i];
const char* name = settings->Name;
if (const char* p = strstr(name, "###")) // Skip to the "###" marker if any. We don't skip past to match the behavior of GetID()
name = p;
buf->appendf("[%s][%s]\n", handler->TypeName, name);
if (settings->ViewportId != 0 && settings->ViewportId != ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
{
buf->appendf("ViewportPos=%d,%d\n", (int)settings->ViewportPos.x, (int)settings->ViewportPos.y);
buf->appendf("ViewportId=0x%08X\n", settings->ViewportId);
}
if (settings->Pos.x != 0.0f || settings->Pos.y != 0.0f || settings->ViewportId == ImGui::IMGUI_VIEWPORT_DEFAULT_ID)
buf->appendf("Pos=%d,%d\n", (int)settings->Pos.x, (int)settings->Pos.y);
if (settings->Size.x != 0.0f || settings->Size.y != 0.0f)
buf->appendf("Size=%d,%d\n", (int)settings->Size.x, (int)settings->Size.y);
buf->appendf("Collapsed=%d\n", settings->Collapsed);
if (settings->DockId != 0)
{
// Write DockId as 4 digits if possible. Automatic DockId are small numbers, but full explicit DockSpace() are full ImGuiID range.
if (settings->DockOrder == -1)
buf->appendf("DockId=0x%08X\n", settings->DockId);
else
buf->appendf("DockId=0x%08X,%d\n", settings->DockId, settings->DockOrder);
if (settings->ClassId != 0)
buf->appendf("ClassId=0x%08X\n", settings->ClassId);
}
buf->appendf("\n");
}
}
//-----------------------------------------------------------------------------
// [SECTION] PLATFORM DEPENDENT HELPERS
//-----------------------------------------------------------------------------
#if defined(_WIN32) && !defined(_WINDOWS_) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && (!defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS) || !defined(IMGUI_DISABLE_WIN32_DEFAULT_IME_FUNCTIONS))
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef __MINGW32__
#include <Windows.h>
#else
#include <windows.h>
#endif
#endif
// Win32 API clipboard implementation
#if defined(_WIN32) && !defined(IMGUI_DISABLE_WIN32_FUNCTIONS) && !defined(IMGUI_DISABLE_WIN32_DEFAULT_CLIPBOARD_FUNCTIONS)
#ifdef _MSC_VER
#pragma comment(lib, "user32")
#endif
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
static ImVector<char> buf_local;
buf_local.clear();
if (!::OpenClipboard(NULL))
return NULL;
HANDLE wbuf_handle = ::GetClipboardData(CF_UNICODETEXT);
if (wbuf_handle == NULL)
{
::CloseClipboard();
return NULL;
}
if (ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle))
{
int buf_len = ImTextCountUtf8BytesFromStr(wbuf_global, NULL) + 1;
buf_local.resize(buf_len);
ImTextStrToUtf8(buf_local.Data, buf_len, wbuf_global, NULL);
}
::GlobalUnlock(wbuf_handle);
::CloseClipboard();
return buf_local.Data;
}
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
if (!::OpenClipboard(NULL))
return;
const int wbuf_length = ImTextCountCharsFromUtf8(text, NULL) + 1;
HGLOBAL wbuf_handle = ::GlobalAlloc(GMEM_MOVEABLE, (SIZE_T)wbuf_length * sizeof(ImWchar));
if (wbuf_handle == NULL)
{
::CloseClipboard();
return;
}
ImWchar* wbuf_global = (ImWchar*)::GlobalLock(wbuf_handle);
ImTextStrFromUtf8(wbuf_global, wbuf_length, text, NULL);
::GlobalUnlock(wbuf_handle);
::EmptyClipboard();
if (::SetClipboardData(CF_UNICODETEXT, wbuf_handle) == NULL)
::GlobalFree(wbuf_handle);
::CloseClipboard();
}
#else
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static const char* GetClipboardTextFn_DefaultImpl(void*)
{
ImGuiContext& g = *GImGui;
return g.PrivateClipboard.empty() ? NULL : g.PrivateClipboard.begin();
}
// Local ImGui-only clipboard implementation, if user hasn't defined better clipboard handlers
static void SetClipboardTextFn_DefaultImpl(void*, const char* text)
{
ImGuiContext& g = *GImGui;
g.PrivateClipboard.clear();
const char* text_end = text + strlen(text);
g.PrivateClipboard.resize((int)(text_end - text) + 1);
memcpy(&g.PrivateClipboard[0], text, (size_t)(text_end - text));
g.PrivateClipboard[(int)(text_end - text)] = 0;
}
#endif
//-----------------------------------------------------------------------------
// [SECTION] METRICS/DEBUG WINDOW
//-----------------------------------------------------------------------------
static void RenderViewportThumbnail(ImDrawList* draw_list, ImGuiViewportP* viewport, const ImRect& bb)
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
ImVec2 scale = bb.GetSize() / viewport->Size;
ImVec2 off = bb.Min - viewport->Pos * scale;
float alpha_mul = viewport->PlatformWindowMinimized ? 0.30f : 1.00f;
window->DrawList->AddRectFilled(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul * 0.40f));
for (int i = 0; i != g.Windows.Size; i++)
{
ImGuiWindow* thumb_window = g.Windows[i];
if (!thumb_window->WasActive || ((thumb_window->Flags & ImGuiWindowFlags_ChildWindow)))
continue;
if (thumb_window->SkipItems && (thumb_window->Flags & ImGuiWindowFlags_ChildWindow)) // FIXME-DOCK: Skip hidden docked windows. Identify those betters.
continue;
if (thumb_window->Viewport != viewport)
continue;
ImRect thumb_r = thumb_window->Rect();
ImRect title_r = thumb_window->TitleBarRect();
ImRect thumb_r_scaled = ImRect(ImFloor(off + thumb_r.Min * scale), ImFloor(off + thumb_r.Max * scale));
ImRect title_r_scaled = ImRect(ImFloor(off + title_r.Min * scale), ImFloor(off + ImVec2(title_r.Max.x, title_r.Min.y) * scale) + ImVec2(0,5)); // Exaggerate title bar height
thumb_r_scaled.ClipWithFull(bb);
title_r_scaled.ClipWithFull(bb);
const bool window_is_focused = (g.NavWindow && thumb_window->RootWindowForTitleBarHighlight == g.NavWindow->RootWindowForTitleBarHighlight);
window->DrawList->AddRectFilled(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_WindowBg, alpha_mul));
window->DrawList->AddRectFilled(title_r_scaled.Min, title_r_scaled.Max, ImGui::GetColorU32(window_is_focused ? ImGuiCol_TitleBgActive : ImGuiCol_TitleBg, alpha_mul));
window->DrawList->AddRect(thumb_r_scaled.Min, thumb_r_scaled.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
if (ImGuiWindow* window_for_title = GetWindowForTitleDisplay(thumb_window))
window->DrawList->AddText(g.Font, g.FontSize * 1.0f, title_r_scaled.Min, ImGui::GetColorU32(ImGuiCol_Text, alpha_mul), window_for_title->Name, ImGui::FindRenderedTextEnd(window_for_title->Name));
}
draw_list->AddRect(bb.Min, bb.Max, ImGui::GetColorU32(ImGuiCol_Border, alpha_mul));
}
void ImGui::ShowViewportThumbnails()
{
ImGuiContext& g = *GImGui;
ImGuiWindow* window = g.CurrentWindow;
// We don't display full monitor bounds (we could, but it often looks awkward), instead we display just enough to cover all of our viewports.
float SCALE = 1.0f / 8.0f;
ImRect bb_full;
//for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
// bb_full.Add(GetPlatformMonitorMainRect(g.PlatformIO.Monitors[n]));
for (int n = 0; n < g.Viewports.Size; n++)
bb_full.Add(g.Viewports[n]->GetRect());
ImVec2 p = window->DC.CursorPos;
ImVec2 off = p - bb_full.Min * SCALE;
//for (int n = 0; n < g.PlatformIO.Monitors.Size; n++)
// window->DrawList->AddRect(off + g.PlatformIO.Monitors[n].MainPos * SCALE, off + (g.PlatformIO.Monitors[n].MainPos + g.PlatformIO.Monitors[n].MainSize) * SCALE, ImGui::GetColorU32(ImGuiCol_Border));
for (int n = 0; n < g.Viewports.Size; n++)
{
ImGuiViewportP* viewport = g.Viewports[n];
ImRect viewport_draw_bb(off + (viewport->Pos) * SCALE, off + (viewport->Pos + viewport->Size) * SCALE);
RenderViewportThumbnail(window->DrawList, viewport, viewport_draw_bb);
}
ImGui::Dummy(bb_full.GetSize() * SCALE);
}
void ImGui::ShowMetricsWindow(bool* p_open)
{
if (!ImGui::Begin("ImGui Metrics", p_open))
{
ImGui::End();
return;
}
static bool show_draw_cmd_clip_rects = true;
static bool show_window_begin_order = false;
ImGuiIO& io = ImGui::GetIO();
ImGui::Text("Dear ImGui %s", ImGui::GetVersion());
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / io.Framerate, io.Framerate);
ImGui::Text("%d vertices, %d indices (%d triangles)", io.MetricsRenderVertices, io.MetricsRenderIndices, io.MetricsRenderIndices / 3);
ImGui::Text("%d active windows (%d visible)", io.MetricsActiveWindows, io.MetricsRenderWindows);
ImGui::Text("%d allocations", io.MetricsActiveAllocations);
ImGui::Checkbox("Show clipping rectangles when hovering draw commands", &show_draw_cmd_clip_rects);
ImGui::Checkbox("Ctrl shows window begin order", &show_window_begin_order);
ImGui::Separator();
struct Funcs
{
static void NodeDrawList(ImGuiWindow* window, ImGuiViewportP* viewport, ImDrawList* draw_list, const char* label)
{
bool node_open = ImGui::TreeNode(draw_list, "%s: '%s' %d vtx, %d indices, %d cmds", label, draw_list->_OwnerName ? draw_list->_OwnerName : "", draw_list->VtxBuffer.Size, draw_list->IdxBuffer.Size, draw_list->CmdBuffer.Size);
if (draw_list == ImGui::GetWindowDrawList())
{
ImGui::SameLine();
ImGui::TextColored(ImVec4(1.0f,0.4f,0.4f,1.0f), "CURRENTLY APPENDING"); // Can't display stats for active draw list! (we don't have the data double-buffered)
if (node_open) ImGui::TreePop();
return;
}
ImDrawList* overlay_draw_list = viewport ? GetOverlayDrawList(viewport) : NULL; // Render additional visuals into the top-most draw list
if (window && overlay_draw_list && ImGui::IsItemHovered())
overlay_draw_list->AddRect(window->Pos, window->Pos + window->Size, IM_COL32(255, 255, 0, 255));
if (!node_open)
return;
int elem_offset = 0;
for (const ImDrawCmd* pcmd = draw_list->CmdBuffer.begin(); pcmd < draw_list->CmdBuffer.end(); elem_offset += pcmd->ElemCount, pcmd++)
{
if (pcmd->UserCallback == NULL && pcmd->ElemCount == 0)
continue;
if (pcmd->UserCallback)
{
ImGui::BulletText("Callback %p, user_data %p", pcmd->UserCallback, pcmd->UserCallbackData);
continue;
}
ImDrawIdx* idx_buffer = (draw_list->IdxBuffer.Size > 0) ? draw_list->IdxBuffer.Data : NULL;
bool pcmd_node_open = ImGui::TreeNode((void*)(pcmd - draw_list->CmdBuffer.begin()), "Draw %4d %s vtx, tex 0x%p, clip_rect (%4.0f,%4.0f)-(%4.0f,%4.0f)", pcmd->ElemCount, draw_list->IdxBuffer.Size > 0 ? "indexed" : "non-indexed", pcmd->TextureId, pcmd->ClipRect.x, pcmd->ClipRect.y, pcmd->ClipRect.z, pcmd->ClipRect.w);
if (show_draw_cmd_clip_rects && overlay_draw_list && ImGui::IsItemHovered())
{
ImRect clip_rect = pcmd->ClipRect;
ImRect vtxs_rect;
for (int i = elem_offset; i < elem_offset + (int)pcmd->ElemCount; i++)
vtxs_rect.Add(draw_list->VtxBuffer[idx_buffer ? idx_buffer[i] : i].pos);
clip_rect.Floor(); overlay_draw_list->AddRect(clip_rect.Min, clip_rect.Max, IM_COL32(255,255,0,255));
vtxs_rect.Floor(); overlay_draw_list->AddRect(vtxs_rect.Min, vtxs_rect.Max, IM_COL32(255,0,255,255));
}
if (!pcmd_node_open)
continue;
// Display individual triangles/vertices. Hover on to get the corresponding triangle highlighted.
ImGuiListClipper clipper(pcmd->ElemCount/3); // Manually coarse clip our print out of individual vertices to save CPU, only items that may be visible.
while (clipper.Step())
for (int prim = clipper.DisplayStart, idx_i = elem_offset + clipper.DisplayStart*3; prim < clipper.DisplayEnd; prim++)
{
char buf[300];
char *buf_p = buf, *buf_end = buf + IM_ARRAYSIZE(buf);
ImVec2 triangles_pos[3];
for (int n = 0; n < 3; n++, idx_i++)
{
int vtx_i = idx_buffer ? idx_buffer[idx_i] : idx_i;
ImDrawVert& v = draw_list->VtxBuffer[vtx_i];
triangles_pos[n] = v.pos;
buf_p += ImFormatString(buf_p, buf_end - buf_p, "%s %04d: pos (%8.2f,%8.2f), uv (%.6f,%.6f), col %08X\n",
(n == 0) ? "idx" : " ", idx_i, v.pos.x, v.pos.y, v.uv.x, v.uv.y, v.col);
}
ImGui::Selectable(buf, false);
if (overlay_draw_list && ImGui::IsItemHovered())
{
ImDrawListFlags backup_flags = overlay_draw_list->Flags;
overlay_draw_list->Flags &= ~ImDrawListFlags_AntiAliasedLines; // Disable AA on triangle outlines at is more readable for very large and thin triangles.
overlay_draw_list->AddPolyline(triangles_pos, 3, IM_COL32(255,255,0,255), true, 1.0f);
overlay_draw_list->Flags = backup_flags;
}
}
ImGui::TreePop();
}
ImGui::TreePop();
}
static void NodeWindows(ImVector<ImGuiWindow*>& windows, const char* label)
{
if (!ImGui::TreeNode(label, "%s (%d)", label, windows.Size))
return;
for (int i = 0; i < windows.Size; i++)
Funcs::NodeWindow(windows[i], "Window");
ImGui::TreePop();
}
static void NodeWindow(ImGuiWindow* window, const char* label)
{
if (!ImGui::TreeNode(window, "%s '%s', %d @ 0x%p", label, window->Name, window->Active || window->WasActive, window))
return;
ImGuiWindowFlags flags = window->Flags;
NodeDrawList(window, window->Viewport, window->DrawList, "DrawList");
ImGui::BulletText("Pos: (%.1f,%.1f), Size: (%.1f,%.1f), SizeContents (%.1f,%.1f)", window->Pos.x, window->Pos.y, window->Size.x, window->Size.y, window->SizeContents.x, window->SizeContents.y);
ImGui::BulletText("Flags: 0x%08X (%s%s%s%s%s%s%s%s%s..)", flags,
(flags & ImGuiWindowFlags_ChildWindow) ? "Child " : "", (flags & ImGuiWindowFlags_Tooltip) ? "Tooltip " : "", (flags & ImGuiWindowFlags_Popup) ? "Popup " : "",
(flags & ImGuiWindowFlags_Modal) ? "Modal " : "", (flags & ImGuiWindowFlags_ChildMenu) ? "ChildMenu " : "", (flags & ImGuiWindowFlags_NoSavedSettings) ? "NoSavedSettings " : "",
(flags & ImGuiWindowFlags_NoMouseInputs)? "NoMouseInputs":"", (flags & ImGuiWindowFlags_NoNavInputs) ? "NoNavInputs" : "", (flags & ImGuiWindowFlags_AlwaysAutoResize) ? "AlwaysAutoResize" : "");
ImGui::BulletText("Scroll: (%.2f/%.2f,%.2f/%.2f)", window->Scroll.x, GetWindowScrollMaxX(window), window->Scroll.y, GetWindowScrollMaxY(window));
ImGui::BulletText("Active: %d/%d, WriteAccessed: %d, BeginOrderWithinContext: %d", window->Active, window->WasActive, window->WriteAccessed, (window->Active || window->WasActive) ? window->BeginOrderWithinContext : -1);
ImGui::BulletText("Appearing: %d, Hidden: %d (Reg %d Resize %d), SkipItems: %d", window->Appearing, window->Hidden, window->HiddenFramesRegular, window->HiddenFramesForResize, window->SkipItems);
ImGui::BulletText("NavLastIds: 0x%08X,0x%08X, NavLayerActiveMask: %X", window->NavLastIds[0], window->NavLastIds[1], window->DC.NavLayerActiveMask);
ImGui::BulletText("NavLastChildNavWindow: %s", window->NavLastChildNavWindow ? window->NavLastChildNavWindow->Name : "NULL");
if (!window->NavRectRel[0].IsInverted())
ImGui::BulletText("NavRectRel[0]: (%.1f,%.1f)(%.1f,%.1f)", window->NavRectRel[0].Min.x, window->NavRectRel[0].Min.y, window->NavRectRel[0].Max.x, window->NavRectRel[0].Max.y);
else
ImGui::BulletText("NavRectRel[0]: <None>");
ImGui::BulletText("Viewport: %d%s, ViewportId: 0x%08X, ViewportPos: (%.1f,%.1f)", window->Viewport ? window->Viewport->Idx : -1, window->ViewportOwned ? " (Owned)" : "", window->ViewportId, window->ViewportPos.x, window->ViewportPos.y);
ImGui::BulletText("ViewportMonitor: %d", window->Viewport ? window->Viewport->PlatformMonitor : -1);
ImGui::BulletText("DockId: 0x%04X, DockOrder: %d, %s: 0x%p, Act: %d, Vis: %d", window->DockId, window->DockOrder, window->DockNodeAsHost ? "DockNodeAsHost" : "DockNode", window->DockNodeAsHost ? window->DockNodeAsHost : window->DockNode, window->DockIsActive, window->DockTabIsVisible);
if (window->RootWindow != window) NodeWindow(window->RootWindow, "RootWindow");
if (window->RootWindowDockStop != window->RootWindow) NodeWindow(window->RootWindowDockStop, "RootWindowDockStop");
if (window->ParentWindow != NULL) NodeWindow(window->ParentWindow, "ParentWindow");
if (window->DC.ChildWindows.Size > 0) NodeWindows(window->DC.ChildWindows, "ChildWindows");
if (window->ColumnsStorage.Size > 0 && ImGui::TreeNode("Columns", "Columns sets (%d)", window->ColumnsStorage.Size))
{
for (int n = 0; n < window->ColumnsStorage.Size; n++)
{
const ImGuiColumnsSet* columns = &window->ColumnsStorage[n];
if (ImGui::TreeNode((void*)(uintptr_t)columns->ID, "Columns Id: 0x%08X, Count: %d, Flags: 0x%04X", columns->ID, columns->Count, columns->Flags))
{
ImGui::BulletText("Width: %.1f (MinX: %.1f, MaxX: %.1f)", columns->MaxX - columns->MinX, columns->MinX, columns->MaxX);
for (int column_n = 0; column_n < columns->Columns.Size; column_n++)
ImGui::BulletText("Column %02d: OffsetNorm %.3f (= %.1f px)", column_n, columns->Columns[column_n].OffsetNorm, OffsetNormToPixels(columns, columns->Columns[column_n].OffsetNorm));
ImGui::TreePop();
}
}
ImGui::TreePop();
}
ImGui::BulletText("Storage: %d bytes", window->StateStorage.Data.Size * (int)sizeof(ImGuiStorage::Pair));
ImGui::TreePop();
}
static void NodeViewport(ImGuiViewportP* viewport)
{
ImGui::SetNextTreeNodeOpen(true, ImGuiCond_Once);
if (ImGui::TreeNode((void*)(intptr_t)viewport->ID, "Viewport #%d, ID: 0x%08X, Parent: 0x%08X, Window: \"%s\"", viewport->Idx, viewport->ID, viewport->ParentViewportId, viewport->Window ? viewport->Window->Name : "N/A"))
{
ImGuiWindowFlags flags = viewport->Flags;
ImGui::BulletText("Pos: (%.0f,%.0f), Size: (%.0f,%.0f), Monitor: %d, DpiScale: %.0f%%", viewport->Pos.x, viewport->Pos.y, viewport->Size.x, viewport->Size.y, viewport->PlatformMonitor, viewport->DpiScale * 100.0f);
if (viewport->Idx > 0) { ImGui::SameLine(); if (ImGui::SmallButton("Reset Pos")) { viewport->Pos = ImVec2(200,200); if (viewport->Window) viewport->Window->Pos = ImVec2(200,200); } }
ImGui::BulletText("Flags: 0x%04X =%s%s%s%s%s%s", viewport->Flags,
(flags & ImGuiViewportFlags_CanHostOtherWindows) ? " CanHostOtherWindows" : "", (flags & ImGuiViewportFlags_NoDecoration) ? " NoDecoration" : "",
(flags & ImGuiViewportFlags_NoFocusOnAppearing) ? " NoFocusOnAppearing" : "", (flags & ImGuiViewportFlags_NoInputs) ? " NoInputs" : "",
(flags & ImGuiViewportFlags_NoRendererClear) ? " NoRendererClear" : "", viewport->PlatformWindowMinimized ? ", PlatformWindowMinimized" : "");
for (int layer_i = 0; layer_i < IM_ARRAYSIZE(viewport->DrawDataBuilder.Layers); layer_i++)
for (int draw_list_i = 0; draw_list_i < viewport->DrawDataBuilder.Layers[layer_i].Size; draw_list_i++)
Funcs::NodeDrawList(NULL, viewport, viewport->DrawDataBuilder.Layers[layer_i][draw_list_i], "DrawList");
ImGui::TreePop();
}
}
};
// Access private state, we are going to display the draw lists from last frame
ImGuiContext& g = *GImGui;
Funcs::NodeWindows(g.Windows, "Windows");
if (ImGui::TreeNode("Viewport", "Viewports (%d)", g.Viewports.Size))
{
ImGui::Indent(ImGui::GetTreeNodeToLabelSpacing());
ImGui::ShowViewportThumbnails();
ImGui::Unindent(ImGui::GetTreeNodeToLabelSpacing());
if (g.PlatformIO.Monitors.Size > 0 && ImGui::TreeNode("Monitors", "Monitors (%d)", g.PlatformIO.Monitors.Size))
{
ImGui::TextWrapped("(When viewports are enabled, imgui needs uses monitor data to position popup/tooltips so they don't straddle monitors.)");
for (int i = 0; i < g.PlatformIO.Monitors.Size; i++)
{
const ImGuiPlatformMonitor& mon = g.PlatformIO.Monitors[i];
ImGui::BulletText("Monitor #%d: DPI %.0f%%\n MainMin (%.0f,%.0f), MainMax (%.0f,%.0f), MainSize (%.0f,%.0f)\n WorkMin (%.0f,%.0f), WorkMax (%.0f,%.0f), WorkSize (%.0f,%.0f)",
i, mon.DpiScale * 100.0f,
mon.MainPos.x, mon.MainPos.y, mon.MainPos.x + mon.MainSize.x, mon.MainPos.y + mon.MainSize.y, mon.MainSize.x, mon.MainSize.y,
mon.WorkPos.x, mon.WorkPos.y, mon.WorkPos.x + mon.WorkSize.x, mon.WorkPos.y + mon.WorkSize.y, mon.WorkSize.x, mon.WorkSize.y);
}
ImGui::TreePop();
}
for (int i = 0; i < g.Viewports.Size; i++)
Funcs::NodeViewport(g.Viewports[i]);
ImGui::TreePop();
}
if (ImGui::TreeNode("Popups", "Popups (%d)", g.OpenPopupStack.Size))
{
for (int i = 0; i < g.OpenPopupStack.Size; i++)
{
ImGuiWindow* window = g.OpenPopupStack[i].Window;
ImGui::BulletText("PopupID: %08x, Window: '%s'%s%s", g.OpenPopupStack[i].PopupId, window ? window->Name : "NULL", window && (window->Flags & ImGuiWindowFlags_ChildWindow) ? " ChildWindow" : "", window && (window->Flags & ImGuiWindowFlags_ChildMenu) ? " ChildMenu" : "");
}
ImGui::TreePop();
}
if (ImGui::TreeNode("Docking & Tab Bars"))
{
ShowDockingDebug();
ImGui::TreePop();
}
if (ImGui::TreeNode("Internal state"))
{
const char* input_source_names[] = { "None", "Mouse", "Nav", "NavKeyboard", "NavGamepad" }; IM_ASSERT(IM_ARRAYSIZE(input_source_names) == ImGuiInputSource_COUNT);
ImGui::Text("HoveredWindow: '%s'", g.HoveredWindow ? g.HoveredWindow->Name : "NULL");
ImGui::Text("HoveredRootWindow: '%s'", g.HoveredRootWindow ? g.HoveredRootWindow->Name : "NULL");
ImGui::Text("HoveredWindowUnderMovingWindow: '%s'", g.HoveredWindowUnderMovingWindow ? g.HoveredWindowUnderMovingWindow->Name : "NULL");
ImGui::Text("HoveredId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d", g.HoveredId, g.HoveredIdPreviousFrame, g.HoveredIdTimer, g.HoveredIdAllowOverlap); // Data is "in-flight" so depending on when the Metrics window is called we may see current frame information or not
ImGui::Text("ActiveId: 0x%08X/0x%08X (%.2f sec), AllowOverlap: %d, Source: %s", g.ActiveId, g.ActiveIdPreviousFrame, g.ActiveIdTimer, g.ActiveIdAllowOverlap, input_source_names[g.ActiveIdSource]);
ImGui::Text("ActiveIdWindow: '%s'", g.ActiveIdWindow ? g.ActiveIdWindow->Name : "NULL");
ImGui::Text("MovingWindow: '%s'", g.MovingWindow ? g.MovingWindow->Name : "NULL");
ImGui::Text("NavWindow: '%s'", g.NavWindow ? g.NavWindow->Name : "NULL");
ImGui::Text("NavId: 0x%08X, NavLayer: %d", g.NavId, g.NavLayer);
ImGui::Text("NavInputSource: %s", input_source_names[g.NavInputSource]);
ImGui::Text("NavActive: %d, NavVisible: %d", g.IO.NavActive, g.IO.NavVisible);
ImGui::Text("NavActivateId: 0x%08X, NavInputId: 0x%08X", g.NavActivateId, g.NavInputId);
ImGui::Text("NavDisableHighlight: %d, NavDisableMouseHover: %d", g.NavDisableHighlight, g.NavDisableMouseHover);
ImGui::Text("NavWindowingTarget: '%s'", g.NavWindowingTarget ? g.NavWindowingTarget->Name : "NULL");
ImGui::Text("DragDrop: %d, SourceId = 0x%08X, Payload \"%s\" (%d bytes)", g.DragDropActive, g.DragDropPayload.SourceId, g.DragDropPayload.DataType, g.DragDropPayload.DataSize);
ImGui::Text("MouseViewport: 0x%08X (UserHovered 0x%08X, LastHovered 0x%08X)", g.MouseViewport->ID, g.IO.MouseHoveredViewport, g.MouseLastHoveredViewport ? g.MouseLastHoveredViewport->ID : 0);
ImGui::TreePop();
}
if (g.IO.KeyCtrl && show_window_begin_order)
{
for (int n = 0; n < g.Windows.Size; n++)
{
ImGuiWindow* window = g.Windows[n];
if (!window->WasActive || ((window->Flags & ImGuiWindowFlags_ChildWindow) && window->DockNode == NULL))
continue;
char buf[64] = "";
char* p = buf;
p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Order: %d\n", window->BeginOrderWithinContext);
ImDrawList* overlay_draw_list = GetOverlayDrawList(window->Viewport);
overlay_draw_list->AddRectFilled(window->Pos - ImVec2(1, 1), window->Pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
overlay_draw_list->AddText(NULL, 0.0f, window->Pos, IM_COL32(255, 255, 255, 255), buf);
}
}
ImGui::End();
}
void ImGui::ShowDockingDebug()
{
ImGuiContext* ctx = GImGui;
ImGuiContext& g = *ctx;
ImGuiDockContext* dc = ctx->DockContext;
struct Funcs
{
static void NodeDockNode(ImGuiDockNode* node, const char* label)
{
ImGui::SetNextTreeNodeOpen(true, ImGuiCond_Once);
bool open;
if (node->Windows.Size > 0)
open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %d windows (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", node->Windows.Size, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
else
open = ImGui::TreeNode((void*)(intptr_t)node->ID, "%s 0x%04X%s: %s split (vis: '%s')", label, node->ID, node->IsVisible ? "" : " (hidden)", (node->SplitAxis == ImGuiAxis_X) ? "horizontal" : (node->SplitAxis == ImGuiAxis_Y) ? "vertical" : "n/a", node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
if (open)
{
IM_ASSERT(node->ChildNodes[0] == NULL || node->ChildNodes[0]->ParentNode == node);
IM_ASSERT(node->ChildNodes[1] == NULL || node->ChildNodes[1]->ParentNode == node);
ImGui::BulletText("Pos (%.0f,%.0f), Size (%.0f, %.0f) Ref (%.0f, %.0f)",
node->Pos.x, node->Pos.y, node->Size.x, node->Size.y, node->SizeRef.x, node->SizeRef.y);
ImGui::BulletText("VisibleWindow: 0x%08X %s", node->VisibleWindow ? node->VisibleWindow->ID : 0, node->VisibleWindow ? node->VisibleWindow->Name : "NULL");
ImGui::BulletText("SelectedTabID: 0x%08X", node->SelectedTabID);
ImGui::BulletText("LastFocusedNodeID: 0x%08X", node->LastFocusedNodeID);
ImGui::BulletText("Flags 0x%02X%s%s%s%s",
node->Flags, node->IsDockSpace() ? ", IsDockSpace" : "", node->IsCentralNode ? ", IsCentralNode" : "",
(GImGui->FrameCount - node->LastFrameAlive < 2) ? ", IsAlive" : "", (GImGui->FrameCount - node->LastFrameActive < 2) ? ", IsActive" : "");
if (node->ChildNodes[0])
NodeDockNode(node->ChildNodes[0], "Child[0]");
if (node->ChildNodes[1])
NodeDockNode(node->ChildNodes[1], "Child[1]");
if (node->TabBar)
NodeTabBar(node->TabBar);
ImGui::TreePop();
}
}
static void NodeTabBar(ImGuiTabBar* tab_bar)
{
// Standalone tab bars (not associated to docking/windows functionality) currently hold no discernible strings.
char buf[256];
char* p = buf;
const char* buf_end = buf + IM_ARRAYSIZE(buf);
p += ImFormatString(p, buf_end - p, "TabBar (%d tabs)%s",
tab_bar->Tabs.Size, (tab_bar->PrevFrameVisible < ImGui::GetFrameCount() - 2) ? " *Inactive*" : "");
if (tab_bar->Flags & ImGuiTabBarFlags_DockNode)
{
p += ImFormatString(p, buf_end - p, " { ");
for (int tab_n = 0; tab_n < ImMin(tab_bar->Tabs.Size, 3); tab_n++)
p += ImFormatString(p, buf_end - p, "%s'%s'", tab_n > 0 ? ", " : "", tab_bar->Tabs[tab_n].Window->Name);
p += ImFormatString(p, buf_end - p, (tab_bar->Tabs.Size > 3) ? " ... }" : " } ");
}
if (ImGui::TreeNode(tab_bar, "%s", buf))
{
for (int tab_n = 0; tab_n < tab_bar->Tabs.Size; tab_n++)
{
const ImGuiTabItem* tab = &tab_bar->Tabs[tab_n];
ImGui::PushID(tab);
if (ImGui::SmallButton("<")) { TabBarQueueChangeTabOrder(tab_bar, tab, -1); } ImGui::SameLine(0, 2);
if (ImGui::SmallButton(">")) { TabBarQueueChangeTabOrder(tab_bar, tab, +1); } ImGui::SameLine();
ImGui::Text("%02d%c Tab 0x%08X '%s'", tab_n, (tab->ID == tab_bar->SelectedTabId) ? '*' : ' ', tab->ID, tab->Window ? tab->Window->Name : "N/A");
ImGui::PopID();
}
ImGui::TreePop();
}
}
};
static bool show_window_dock_info = false;
ImGui::Checkbox("Ctrl shows window dock info", &show_window_dock_info);
if (ImGui::TreeNode("Dock nodes"))
{
if (ImGui::SmallButton("Clear settings")) { DockContextClearNodes(&g, 0, true); }
ImGui::SameLine();
if (ImGui::SmallButton("Rebuild all")) { dc->WantFullRebuild = true; }
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
if (node->IsRootNode())
Funcs::NodeDockNode(node, "Node");
ImGui::TreePop();
}
if (ImGui::TreeNode("TabBars", "Tab Bars (%d)", g.TabBars.Data.Size))
{
for (int n = 0; n < g.TabBars.Data.Size; n++)
Funcs::NodeTabBar(g.TabBars.GetByIndex(n));
ImGui::TreePop();
}
if (ImGui::TreeNode("Settings"))
{
if (ImGui::SmallButton("Refresh"))
SaveIniSettingsToMemory();
ImGui::SameLine();
if (ImGui::SmallButton("Save to disk"))
SaveIniSettingsToDisk(g.IO.IniFilename);
ImGui::Separator();
ImGui::Text("Docked Windows:");
for (int n = 0; n < g.SettingsWindows.Size; n++)
if (g.SettingsWindows[n].DockId != 0)
ImGui::BulletText("Window '%s' -> DockId %08X", g.SettingsWindows[n].Name, g.SettingsWindows[n].DockId);
ImGui::Separator();
ImGui::Text("Dock Nodes:");
for (int n = 0; n < dc->SettingsNodes.Size; n++)
{
ImGuiDockNodeSettings* settings = &dc->SettingsNodes[n];
const char* selected_tab_name = NULL;
if (settings->SelectedTabID)
{
if (ImGuiWindow* window = FindWindowByID(settings->SelectedTabID))
selected_tab_name = window->Name;
else if (ImGuiWindowSettings* window_settings = FindWindowSettings(settings->SelectedTabID))
selected_tab_name = window_settings->Name;
}
ImGui::BulletText("Node %08X, Parent %08X, SelectedTab %08X ('%s')", settings->ID, settings->ParentID, settings->SelectedTabID, selected_tab_name ? selected_tab_name : settings->SelectedTabID ? "N/A" : "");
}
ImGui::TreePop();
}
if (g.IO.KeyCtrl && show_window_dock_info)
{
for (int n = 0; n < dc->Nodes.Data.Size; n++)
if (ImGuiDockNode* node = (ImGuiDockNode*)dc->Nodes.Data[n].val_p)
{
ImGuiDockNode* root_node = DockNodeGetRootNode(node);
if (ImGuiDockNode* hovered_node = DockNodeTreeFindNodeByPos(root_node, g.IO.MousePos))
if (hovered_node != node)
continue;
char buf[64] = "";
char* p = buf;
ImDrawList* overlay_draw_list = node->HostWindow ? GetOverlayDrawList(node->HostWindow) : GetOverlayDrawList((ImGuiViewportP*)GetMainViewport());
p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "DockId: %X%s\n", node->ID, node->IsCentralNode ? " *CentralNode*" : "");
p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "Size: (%.0f, %.0f)\n", node->Size.x, node->Size.y);
p += ImFormatString(p, buf + IM_ARRAYSIZE(buf) - p, "SizeRef: (%.0f, %.0f)\n", node->SizeRef.x, node->SizeRef.y);
int depth = DockNodeGetDepth(node);
overlay_draw_list->AddRect(node->Pos + ImVec2(3,3) * (float)depth, node->Pos + node->Size - ImVec2(3,3) * (float)depth, IM_COL32(200, 100, 100, 255));
ImVec2 pos = node->Pos + ImVec2(3,3) * (float)depth;
overlay_draw_list->AddRectFilled(pos - ImVec2(1, 1), pos + CalcTextSize(buf) + ImVec2(1, 1), IM_COL32(200, 100, 100, 255));
overlay_draw_list->AddText(NULL, 0.0f, pos, IM_COL32(255, 255, 255, 255), buf);
}
}
}
//-----------------------------------------------------------------------------
// Include imgui_user.inl at the end of imgui.cpp to access private data/functions that aren't exposed.
// Prefer just including imgui_internal.h from your code rather than using this define. If a declaration is missing from imgui_internal.h add it or request it on the github.
#ifdef IMGUI_INCLUDE_IMGUI_USER_INL
#include "imgui_user.inl"
#endif
//-----------------------------------------------------------------------------
|
;Tyler Wilding
;DESKTOP-EVD5HKS
;8/8/2016 11:02:59 AM
;Question_C
;Implement the following C++ expression in assembly language, using 32-bit signed
;operands:
; val1 = (val2 / val3) * (val1 + val2)
INCLUDE Irvine32.inc
.data
val1 SDWORD 1
val2 SDWORD 6
val3 SDWORD 3
.code
main PROC
cmp val3, 0
JE divideByZero
mov EAX, val2
cdq
idiv val3
mov EBX, val1
add EBX, val2
imul EBX
call WriteInt
mov val1, EAX
divideByZero:
exit
main ENDP
END main |
// ヘッダのインクルード
// 独自のヘッダ
#include "height_max.h" // class_height_max
// メンバの定義
// メンバ関数max
int class_height_max::max(class_measurable objs[], int size){
// 変数の初期化.
int max_height = -1; // int型max_heightを-1で初期化.
// 幅の最大値を求める.
for (int i = 0; i < size; i++){
// height_を比較
if (max_height < objs[i].height_){ // objs[i].height_が大きい場合.
max_height = objs[i].height_; // objs[i].height_をmax_heightに格納.
}
}
// 最大値を返す.
return max_height; // max_heightを返す.
}
|
swap:
pushq (%RSI)
pushq (%RDI)
popq (%RSI)
popq (%RDI)
retq
|
; Small C+ Z88 Support Library
;
; Convert signed long to int
; NB. This routine will only work if long < +/-32767ish (obvious)
SECTION code_l_sccz80
PUBLIC l_long2int_s
l_long2int_s:
; copy sign of d into h
ld a,d
xor h
ret p
and $80
xor h
ld h,a
ret
|
SECTION code_clib
SECTION code_fp_math48
PUBLIC _log10
EXTERN cm48_sdccix_log10
defc _log10 = cm48_sdccix_log10
|
; Palettes to be used by various maps.
; Each byte in map_palette_sets.asm refers to one of these palettes.
MapPalettes:
; 0x00: GAMEFREAK_GRAY
RGB 31,31,31
RGB 21,21,21
RGB 12,12,12
RGB 0,0,0
; 0x01: OUTDOOR_GRAY
RGB 27,31,27
RGB 21,21,21
RGB 13,13,13
RGB 7,7,7
; 0x02: OUTDOOR_RED
RGB 27,31,27
RGB 31,19,24
RGB 30,10,6
RGB 7,7,7
; 0x03: OUTDOOR_GREEN
RGB 22,31,10
RGB 12,25,1
RGB 5,14,0
RGB 7,7,7
; 0x04: OUTDOOR_BLUE
RGB 23,23,31
RGB 18,19,31
RGB 13,12,31
RGB 7,7,7
; 0x05: OUTDOOR_YELLOW
RGB 27,31,27
RGB 31,31,7
RGB 31,16,1
RGB 7,7,7
; 0x06: OUTDOOR_BROWN
RGB 27,31,27
RGB 24,18,7
RGB 20,15,3
RGB 7,7,7
; 0x07: OUTDOOR_ROOF
RGB 27,31,27
RGB 20,31,14
RGB 11,23,5
RGB 7,7,7
; 0x08: CRYS_TEXTBOX
RGB 31,31,31
RGB 31,31,31
RGB 31,31,31
RGB 0,0,0
; 0x09: INDOOR_GRAY
RGB 30,28,26
RGB 19,19,19
RGB 13,13,13
RGB 7,7,7
; 0x0a: INDOOR_RED
RGB 30,28,26
RGB 31,19,24
RGB 30,10,6
RGB 7,7,7
; 0x0b: INDOOR_GREEN
RGB 30,28,26
RGB 15,20,1
RGB 9,13,0
RGB 7,7,7
; 0x0c: INDOOR_BLUE
RGB 30,28,26
RGB 15,16,31
RGB 9,9,31
RGB 7,7,7
; 0x0d: INDOOR_YELLOW
RGB 30,28,26
RGB 31,31,7
RGB 31,16,1
RGB 7,7,7
; 0x0e: INDOOR_BROWN
RGB 30,28,26
RGB 21,17,7
RGB 16,13,3
RGB 7,7,7
; 0x0f: INDOOR_LIGHT_BLUE
RGB 30,28,26
RGB 17,19,31
RGB 14,16,31
RGB 7,7,7
; 0x10: MAP_PALETTE_10
RGB 27,31,27
RGB 31,14,28
RGB 31,5,21
RGB 7,7,7
; 0x11: MAP_PALETTE_11
RGB 27,31,27
RGB 24,14,31
RGB 13,7,21
RGB 7,7,7
; 0x12: MAP_PALETTE_12
RGB 27,31,27
RGB 31,19,0
RGB 27,10,5
RGB 7,7,7
; 0x13: MAP_PALETTE_13
RGB 27,31,27
RGB 22,20,10
RGB 17,14,3
RGB 7,7,7
; 0x14: MAP_PALETTE_14
RGB 27,31,27
RGB 25,25,0
RGB 20,17,8
RGB 7,7,7
; 0x15: MAP_PALETTE_15
RGB 27,31,27
RGB 14,17,31
RGB 7,11,15
RGB 7,7,7
; 0x16: MAP_PALETTE_16
RGB 27,31,27
RGB 15,10,31
RGB 7,5,15
RGB 7,7,7
; 0x17: CAVE_GRAY
RGB 15,14,24
RGB 11,11,19
RGB 7,7,12
RGB 0,0,0
; 0x18: CAVE_RED
RGB 15,14,24
RGB 14,7,17
RGB 13,0,8
RGB 0,0,0
; 0x19: CAVE_GREEN
RGB 15,14,24
RGB 8,13,19
RGB 0,11,13
RGB 0,0,0
; 0x1a: CAVE_BLUE
RGB 15,14,24
RGB 5,5,17
RGB 3,3,10
RGB 0,0,0
; 0x1b: CAVE_YELLOW
RGB 30,30,11
RGB 16,14,18
RGB 16,14,10
RGB 0,0,0
; 0x1c: CAVE_BROWN
RGB 15,14,24
RGB 12,9,15
RGB 8,4,5
RGB 0,0,0
; 0x1d: CAVE_LIGHT_BLUE
RGB 15,14,24
RGB 13,12,23
RGB 11,9,20
RGB 0,0,0
; 0x1e: BENCH_GUY_PAL
RGB 31,19,10
RGB 31,19,24
RGB 30,10,6
RGB 7,7,7
; 0x1f: PC_POKEBALL_PAL
RGB 31,31,31
RGB 31,19,10
RGB 30,10,6
RGB 0,0,0
; 0x20: FOREST_ROCKS
RGB 22,31,10
RGB 24,18,7
RGB 20,15,3
RGB 7,7,7
; 0x21: FOREST_TREES
RGB 22,31,10
RGB 20,31,14
RGB 11,23,5
RGB 7,7,7
; 0x22: ALT_TEXTBOX_PAL
RGB 31,31,31
RGB 21,21,21
RGB 13,13,13
RGB 0,0,0
; 0x23: MAP_PALETTE_23
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x24: MAP_PALETTE_24
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x25: MAP_PALETTE_25
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x26: MAP_PALETTE_26
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x27: MAP_PALETTE_27
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x28: MAP_PALETTE_28
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x29: MAP_PALETTE_29
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2a: MAP_PALETTE_2A
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2b: MAP_PALETTE_2B
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2c: MAP_PALETTE_2C
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2d: MAP_PALETTE_2D
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2e: MAP_PALETTE_2E
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x2f: MAP_PALETTE_2F
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x30: MAP_PALETTE_30
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x31: MAP_PALETTE_31
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x32: MAP_PALETTE_32
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x33: MAP_PALETTE_33
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x34: MAP_PALETTE_34
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x35: MAP_PALETTE_35
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x36: MAP_PALETTE_36
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x37: MAP_PALETTE_37
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x38: MAP_PALETTE_38
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x39: MAP_PALETTE_39
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3a: MAP_PALETTE_3A
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3b: MAP_PALETTE_3B
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3c: MAP_PALETTE_3C
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3d: MAP_PALETTE_3D
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3e: MAP_PALETTE_3E
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
; 0x3f: MAP_PALETTE_3F
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
RGB 0,0,0
|
; A284850: a(n) = 4^n - 3^n - n.
; 0,5,34,171,776,3361,14190,58967,242452,989517,4017146,16245763,65514528,263652473,1059392902,4251920559,17050729004,68332056229,273715645458,1096024843355,4387586157880,17560804984785,70274600998814,281192547174151,1125052618233156,4501057761542141
mov $4,$0
sub $0,1
mov $6,2
add $6,$0
cmp $0,1
div $0,2
add $0,1
mov $2,4
sub $3,$0
mov $5,$0
add $5,$4
pow $2,$5
add $3,1
mov $7,3
pow $7,$6
add $3,$7
add $3,$5
lpb $0,1
cmp $0,$2
mov $1,$2
mov $5,1
sub $5,$3
add $1,$5
lpe
sub $1,1
|
; A142151: a(n) = OR{k XOR (n-k): 0<=k<=n}.
; Submitted by Jon Maiga
; 0,1,2,3,6,5,6,7,14,13,14,11,14,13,14,15,30,29,30,27,30,29,30,23,30,29,30,27,30,29,30,31,62,61,62,59,62,61,62,55,62,61,62,59,62,61,62,47,62,61,62,59,62,61,62,55,62,61,62,59,62,61,62,63,126,125,126,123,126,125,126,119,126,125,126,123,126,125,126,111,126,125,126,123,126,125,126,119,126,125,126,123,126,125,126,95,126,125,126,123
add $0,1
seq $0,340632 ; a(n) in binary is a run of 1-bits from the most significant 1-bit of n down to the least significant 1-bit of n, inclusive.
sub $0,1
|
;
; file: dmax.asm
global _dmax
segment _TEXT public align=1 class=CODE use32
; function _dmax
; returns the larger of its two double arguments
; C prototype
; double dmax( double d1, double d2 )
; Parameters:
; d1 - first double
; d2 - second double
; Return value:
; larger of d1 and d2 (in ST0)
; next, some helpful symbols are defined
%define d1 [ebp+8]
%define d2 [ebp+16]
_dmax:
enter 0, 0
fld qword d2
fld qword d1 ; ST0 = d1, ST1 = d2
fcomip st1 ; ST0 = d2
jna short d2_bigger
fcomp st0 ; pop d2 from stack
fld qword d1 ; ST0 = d1
d2_bigger: ; if d2 is bigger, nothing to do
exit:
leave
ret
|
; DRAW OR SPRITE 2 BYTE DEFINITION ROTATED, ON LEFT BORDER
; 01.2006 aralbrec, Sprite Pack v3.0
; sinclair spectrum version
INCLUDE "clib_target_cfg.asm"
SECTION code_clib
SECTION code_temp_sp1
PUBLIC _SP1_DRAW_OR2LB
EXTERN _SP1_DRAW_OR2NR
EXTERN SP1RETSPRDRAW
; following data segment copied into struct sp1_cs
ld hl,0
nop
ld de,0
call _SP1_DRAW_OR2LB
; following draw code called by way of SP1UpdateNow
;
; a = hor rot table
; bc = graphic disp
; hl = graphic def ptr
; de = left graphic def ptr
;
; 32 + 106*4 - 6 + 10 = 460 cycles
_SP1_DRAW_OR2LB:
cp SP1V_ROTTBL/256
jp z, _SP1_DRAW_OR2NR
add hl,bc
ld d,a
; d = shift table
; hl = sprite def (mask,graph) pairs
_SP1Or2LBRotate:
; 0
ld bc,(SP1V_PIXELBUFFER+0)
inc hl
ld e,(hl)
inc hl
ld a,(de)
or c
ld (SP1V_PIXELBUFFER+0),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
or b
ld (SP1V_PIXELBUFFER+1),a
; 1
ld bc,(SP1V_PIXELBUFFER+2)
inc hl
ld e,(hl)
inc hl
ld a,(de)
or c
ld (SP1V_PIXELBUFFER+2),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
or b
ld (SP1V_PIXELBUFFER+3),a
; 2
ld bc,(SP1V_PIXELBUFFER+4)
inc hl
ld e,(hl)
inc hl
ld a,(de)
or c
ld (SP1V_PIXELBUFFER+4),a
inc hl
ld e,(hl)
inc hl
ld a,(de)
or b
ld (SP1V_PIXELBUFFER+5),a
; 3
ld bc,(SP1V_PIXELBUFFER+6)
inc hl
ld e,(hl)
inc hl
ld a,(de)
or c
ld (SP1V_PIXELBUFFER+6),a
inc hl
ld e,(hl)
ld a,(de)
or b
ld (SP1V_PIXELBUFFER+7),a
jp SP1RETSPRDRAW
|
#include <algorithm>
#include <set>
#include "cm_abilities.h"
#include "cm_actor.h"
#include "cm_game_world.h"
#include "cm_logger.h"
#include "cm_effect.h"
#include "cm_random.h"
#include "cm_enemy.h"
namespace cm
{
// AbilitySet
void AbilitySet::SetAbility(int slot, std::unique_ptr<Ability> ability)
{
if (slot >= 0 && slot < Abilities.size())
{
Abilities[slot] = std::move(ability);
}
}
Ability *AbilitySet::AbilityAt(int slot)
{
if (slot < 0 || slot >= 4)
{
return nullptr;
}
return Abilities.at(slot).get();
}
bool AbilitySet::AbilityReady(int slot)
{
return false;
}
void AbilitySet::Reset()
{
std::fill(Abilities.begin(), Abilities.end(), nullptr);
}
int AbilitySet::FreeSlot()
{
int freeSlot = -1;
for (auto i = 0; i < Abilities.size(); i++)
{
if (Abilities.at(i) == nullptr)
{
freeSlot = i;
break;
}
}
return freeSlot;
}
bool AttackAbility::Use(Actor &user, GameWorld &world)
{
auto target = world.GetActor(user.Target);
if (target == nullptr)
{
return false;
}
auto attackRange = 1;
// If the actor has a weaponed equipped, use its range
auto weapon = user.InventoryComp->EquipmentAt(ItemType::OneHand);
if (weapon != nullptr)
{
attackRange = weapon->Range;
}
auto distance = Distance(user.Position, target->Position);
if (distance > attackRange)
{
return false;
}
auto baseDamage = user.Stats.GetAttackRating() / 4;
auto defense = target->Stats.GetDefenseRating() / 6;
int actualDamage = RandomInt(baseDamage / 2, baseDamage * 2) - RandomInt(defense / 2, defense * 2);
if (actualDamage <= 0)
{
actualDamage = 1;
}
// Damage the target
target->CombatComp->Damage({actualDamage, &user}, world);
return true;
}
bool HealAbility::Use(Actor &user, GameWorld &world)
{
user.CombatComp->Heal({static_cast<int>(user.Stats.MaxHP() * 0.4), &user}, world);
return true;
}
bool CleaveAbility::Use(Actor &user, GameWorld &world)
{
// Damage all targets within one tile of the user
auto neighbors = world.GetLevel()->GetNeighbors(user.Position);
for (auto n : neighbors)
{
auto enemy = world.GetActor(n->Position);
if (enemy != nullptr && !enemy->Friendly)
{
// TODO: consider target's defense rating
auto baseDamage = user.Stats.GetAttackRating() / 5;
int actualDamage = RandomInt(baseDamage / 2, baseDamage);
// auto effect = DamageEffect({actualDamage, &user});
// effect.Use(*enemy, world);
user.Target = enemy->Position;
}
}
return true;
}
bool TeleportAbility::Use(Actor &user, GameWorld &world)
{
auto tile = world.GetLevel()->GetTile(user.Target);
if (world.GetActor(tile->Position) != nullptr)
{
return false;
}
if (Distance(user.Position, tile->Position) > 4)
{
return false;
}
if (tile->Walkable)
{
user.Position = tile->Position;
}
return true;
}
bool SlimeSplitAbility::Use(Actor &user, GameWorld &world)
{
auto neighbors = world.GetLevel()->GetNeighbors(user.Position);
if (!neighbors.empty())
{
std::random_shuffle(neighbors.begin(), neighbors.end());
for (auto n : neighbors)
{
if (n->Walkable && world.GetActor(n->Position) == nullptr)
{
auto currentHP = user.Stats.HP();
// Adjust the original slime's max HP to its current HP
user.Stats.SetStatBaseValue(ActorStatType::MaxHealth, currentHP);
// Create a new slime with the same max HP
auto clone = std::make_unique<Slime>(n->Position);
clone->Stats.SetStatBaseValue(ActorStatType::Health, currentHP);
clone->Stats.SetStatBaseValue(ActorStatType::MaxHealth, currentHP);
world.AddEnemy(std::move(clone));
return true;
}
}
}
return false;
}
bool PoisonAuraAbility::Use(Actor &user, GameWorld &world)
{
auto effect = PoisonAuraEffect();
effect.Use(&user, nullptr, &world);
return true;
}
bool ChainLightningAbility::Use(Actor &user, GameWorld &world)
{
auto target = world.GetActor(user.Target);
if (target == nullptr)
{
return false;
}
auto effect = ChainLightningEffect();
effect.Use(&user, target, &world);
return true;
}
std::unique_ptr<Ability> RandomAbility()
{
int r = RandomInt(5);
if (r == 0)
return std::make_unique<HealAbility>();
else if (r == 1)
return std::make_unique<CleaveAbility>();
else if (r == 2)
return std::make_unique<TeleportAbility>();
else if (r == 3)
return std::make_unique<PoisonAuraAbility>();
else if (r == 4)
return std::make_unique<ChainLightningAbility>();
return nullptr;
}
} // namespace cm |
%ifdef CONFIG
{
"RegData": {
"XMM0": ["0x4142434445464748", "0x5152535455565758"],
"XMM1": ["0x4142434445464748", "0x5152535455565758"]
},
"MemoryRegions": {
"0x100000000": "4096"
}
}
%endif
mov rdx, 0xe0000000
mov rax, 0
mov [rdx + 8 * 0], rax
mov [rdx + 8 * 1], rax
mov rax, 0x4142434445464748
mov [rdx + 8 * 2], rax
mov rax, 0x5152535455565758
mov [rdx + 8 * 3], rax
movupd xmm1, [rdx + 8 * 2]
movupd [rdx + 8 * 0], xmm1
movupd xmm0, [rdx + 8 * 0]
hlt
|
; =============================================================================
; BareMetal -- a 64-bit OS written in Assembly for x86-64 systems
; Copyright (C) 2008-2016 Return Infinity -- see LICENSE.TXT
;
; System Call Section -- Accessible to user programs
; =============================================================================
%include "syscalls/disk.asm"
%include "syscalls/input.asm"
%include "syscalls/memory.asm"
%include "syscalls/misc.asm"
%include "syscalls/net.asm"
%include "syscalls/screen.asm"
%include "syscalls/smp.asm"
; =============================================================================
; EOF
|
; A008818: Expansion of (1+2*x^3+x^4)/((1-x^2)^2*(1-x^4)); Molien series for 3-dimensional representation of group 2x = [ 2+,4+ ] = CC_4 = C4.
; 1,0,2,2,5,4,8,8,13,12,18,18,25,24,32,32,41,40,50,50,61,60,72,72,85,84,98,98,113,112,128,128,145,144,162,162,181,180,200,200,221,220,242,242,265,264,288,288,313,312,338,338,365,364,392,392,421,420,450,450,481,480,512,512,545,544,578,578,613,612,648,648,685,684,722,722,761,760,800,800,841,840,882,882,925,924,968,968,1013,1012,1058,1058,1105,1104,1152,1152,1201,1200,1250,1250,1301,1300,1352,1352,1405,1404,1458,1458,1513,1512,1568,1568,1625,1624,1682,1682,1741,1740,1800,1800,1861,1860,1922,1922,1985,1984,2048,2048,2113,2112,2178,2178,2245,2244,2312,2312,2381,2380,2450,2450,2521,2520,2592,2592,2665,2664,2738,2738,2813,2812,2888,2888,2965,2964,3042,3042,3121,3120,3200,3200,3281,3280,3362,3362,3445,3444,3528,3528,3613,3612,3698,3698,3785,3784,3872,3872,3961,3960,4050,4050,4141,4140,4232,4232,4325,4324,4418,4418,4513,4512,4608,4608,4705,4704,4802,4802,4901,4900,5000,5000,5101,5100,5202,5202,5305,5304,5408,5408,5513,5512,5618,5618,5725,5724,5832,5832,5941,5940,6050,6050,6161,6160,6272,6272,6385,6384,6498,6498,6613,6612,6728,6728,6845,6844,6962,6962,7081,7080,7200,7200,7321,7320,7442,7442,7565,7564,7688,7688,7813,7812
mov $3,$0
mov $0,2
mov $1,1
add $3,1
mov $4,2
mov $5,4
lpb $0,1
sub $0,1
pow $1,2
add $1,$3
div $1,2
mov $2,30
mod $3,$4
lpe
div $5,2
add $5,$2
add $1,$5
mul $1,4
sub $1,128
div $1,4
|
; A049716: a(n) = 2*n + 1 - prevprime(2*n + 1).
; Submitted by Jamie Morken(s3)
; 1,2,2,2,4,2,2,4,2,2,4,2,4,6,2,2,4,6,2,4,2,2,4,2,4,6,2,4,6,2,2,4,6,2,4,2,2,4,6,2,4,2,4,6,2,4,6,8,2,4,2,2,4,2,2,4,2,4,6,8,10,12,14,2,4,2,4,6,2,2,4,6,8,10,2,2,4,6,2,4,6,2,4,2,4,6,2,4,6,2,2,4,6,8,10,2,2,4,2,2
mul $0,2
add $0,1
seq $0,64722 ; a(1) = 0; for n >= 2, a(n) = n - (largest prime <= n).
add $0,1
|
//
// Color chooser test program for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2018 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// https://www.fltk.org/COPYING.php
//
// Please see the following page on how to report bugs and issues:
//
// https://www.fltk.org/bugs.php
//
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/fl_show_colormap.H>
#include <FL/Fl_Color_Chooser.H>
#include <FL/Fl_Image.H>
#include <FL/platform.H>
#include <FL/fl_draw.H>
#include <stdlib.h>
#include <stdio.h>
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
#include "list_visuals.cxx"
#endif
int width = 100;
int height = 100;
uchar *image;
Fl_Box *hint;
void make_image() {
image = new uchar[3*width*height];
uchar *p = image;
for (int y = 0; y < height; y++) {
double Y = double(y)/(height-1);
for (int x = 0; x < width; x++) {
double X = double(x)/(width-1);
*p++ = uchar(255*((1-X)*(1-Y))); // red in upper-left
*p++ = uchar(255*((1-X)*Y)); // green in lower-left
*p++ = uchar(255*(X*Y)); // blue in lower-right
}
}
}
class Pens : public Fl_Box {
void draw();
public:
Pens(int X, int Y, int W, int H, const char* L)
: Fl_Box(X,Y,W,H,L) {}
};
void Pens::draw() {
// use every color in the gray ramp:
for (int i = 0; i < 3*8; i++) {
fl_color((Fl_Color)(FL_GRAY_RAMP+i));
fl_line(x()+i, y(), x()+i, y()+h());
}
}
Fl_Color c = FL_GRAY;
#define fullcolor_cell (FL_FREE_COLOR)
void cb1(Fl_Widget *, void *v) {
c = fl_show_colormap(c);
Fl_Box* b = (Fl_Box*)v;
b->color(c);
hint->labelcolor(fl_contrast(FL_BLACK,c));
b->parent()->redraw();
}
void cb2(Fl_Widget *, void *v) {
uchar r,g,b;
Fl::get_color(c,r,g,b);
if (!fl_color_chooser("New color:",r,g,b,3)) return;
c = fullcolor_cell;
Fl::set_color(fullcolor_cell,r,g,b);
Fl_Box* bx = (Fl_Box*)v;
bx->color(fullcolor_cell);
hint->labelcolor(fl_contrast(FL_BLACK,fullcolor_cell));
bx->parent()->redraw();
}
int main(int argc, char ** argv) {
Fl::set_color(fullcolor_cell,145,159,170);
Fl_Window window(400,400);
Fl_Box box(30,30,340,340);
box.box(FL_THIN_DOWN_BOX);
c = fullcolor_cell;
box.color(c);
Fl_Box hintbox(40,40,320,30,"Pick background color with buttons:");
hintbox.align(FL_ALIGN_INSIDE);
hint = &hintbox;
Fl_Button b1(120,80,180,30,"fl_show_colormap()");
b1.callback(cb1,&box);
Fl_Button b2(120,120,180,30,"fl_color_chooser()");
b2.callback(cb2,&box);
Fl_Box image_box(160,190,width,height,0);
make_image();
(new Fl_RGB_Image(image, width, height))->label(&image_box);
Fl_Box b(160,310,120,30,"Example of fl_draw_image()");
Pens p(60,180,3*8,120,"lines");
p.align(FL_ALIGN_TOP);
int i = 1;
if (!Fl::args(argc,argv,i) || i < argc-1) {
printf("usage: %s <switches> visual-number\n"
" - : default visual\n"
" r : call Fl::visual(FL_RGB)\n"
" c : call Fl::own_colormap()\n",argv[0]);
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
printf(" # : use this visual with an empty colormap:\n");
list_visuals();
#endif
puts(Fl::help);
exit(1);
}
if (i!=argc) {
if (argv[i][0] == 'r') {
if (!Fl::visual(FL_RGB)) printf("Fl::visual(FL_RGB) returned false.\n");
} else if (argv[i][0] == 'c') {
Fl::own_colormap();
} else if (argv[i][0] != '-') {
#if !defined(_WIN32) && !defined(__APPLE__) && !defined(__ANDROID__)
int visid = atoi(argv[i]);
fl_open_display();
XVisualInfo templt; int num;
templt.visualid = visid;
fl_visual = XGetVisualInfo(fl_display, VisualIDMask, &templt, &num);
if (!fl_visual) Fl::fatal("No visual with id %d",visid);
fl_colormap = XCreateColormap(fl_display, RootWindow(fl_display,fl_screen),
fl_visual->visual, AllocNone);
fl_xpixel(FL_BLACK); // make sure black is allocated
#else
Fl::fatal("Visual id's not supported on Windows or MacOS.");
#endif
}
}
window.show(argc,argv);
return Fl::run();
}
|
#include "hello.h"
std::string hello() { return "hello"; }
|
; A160927: a(n) = n + reversal(n-1).
; 1,3,5,7,9,11,13,15,17,19,12,23,34,45,56,67,78,89,100,111,23,34,45,56,67,78,89,100,111,122,34,45,56,67,78,89,100,111,122,133,45,56,67,78,89,100,111,122,133,144,56,67,78,89,100,111,122,133,144,155,67,78,89,100
mov $1,$0
seq $1,4086 ; Read n backwards (referred to as R(n) in many sequences).
add $0,$1
add $0,1
|
; A051927: Number of independent vertex sets in the n-prism graph Y_n = K_2 X C_n (n > 2).
; Submitted by Jon Maiga
; 3,1,7,13,35,81,199,477,1155,2785,6727,16237,39203,94641,228487,551613,1331715,3215041,7761799,18738637,45239075,109216785,263672647,636562077,1536796803,3710155681,8957108167,21624372013,52205852195,126036076401,304278004999,734592086397,1773462177795,4281516441985,10336495061767,24954506565517,60245508192803,145445522951121,351136554095047,847718631141213,2046573816377475,4940866263896161,11928306344169799,28797478952235757,69523264248641315,167844007449518385,405211279147678087
mov $2,1
lpb $0
sub $0,1
sub $3,$4
mov $4,$2
mov $2,$3
add $5,1
add $5,$4
mov $3,$5
sub $4,$5
add $5,$2
lpe
mov $0,$2
mul $0,2
add $0,1
|
;-------------------------------------------------
; libScroller
; -----------
;-------------------------------------------------
;---------------------------------------
; UpdateLayerPos
; --------------
; [Input]
; X register : position type
; 0 - Layer1 X
; 2 - Layer1 Y
; 4 - Layer2 X
; 6 - Layer2 Y
;---------------------------------------
UpdateLayerPos:
lda.w $144e|!base2,x
and.w #$00ff
clc
adc.w $1446|!base2,x
sta.w $144e|!base2,x
and.w #$ff00
bpl +
ora.w #$00ff
+ xba
clc
adc.w $1462|!base2,x
sta.w $1462|!base2,x
;--- Invert $08
lda.b $08
eor.w #$ffff
inc a
sta.b $08
rtl
|
; uint __FASTCALL__ zx_aaddr2cx(void *attraddr)
; aralbrec 06.2007
XLIB zx_aaddr2cx
.zx_aaddr2cx
ld a,l
and $1f
ld l,a
ld h,0
ret
|
; A176058: Decimal expansion of (3+sqrt(15))/2.
; Submitted by Jon Maiga
; 3,4,3,6,4,9,1,6,7,3,1,0,3,7,0,8,4,4,2,5,8,9,6,3,2,6,9,9,8,9,1,1,9,9,8,0,5,4,1,6,4,6,0,8,5,2,6,4,5,7,9,5,4,1,3,2,9,3,7,8,6,8,8,3,0,5,6,7,4,1,5,4,5,9,6,8,4,8,9,5,1,6,7,5,9,6,4,3,6,8,8,4,2,9,3,3,6,7,5,8
mov $1,3
mov $2,1
mov $3,$0
mul $3,2
lpb $3
mul $1,$3
mul $2,$3
add $1,$2
mul $2,5
add $2,$1
cmp $6,0
add $5,$6
div $1,$5
mul $1,2
div $2,$5
add $2,$1
sub $3,1
lpe
div $1,2
mul $1,3
mov $4,10
pow $4,$0
div $2,$4
div $1,$2
mod $1,10
mov $0,$1
|
;/*********************** (C) COPYRIGHT 2010 Libraworks *************************
;* File Name : os_cpu_a.asm
;* Author : Librae
;* Version : V1.0
;* Date : 06/10/2010
;* Description : μCOS-II asm port for STM32
;*******************************************************************************/
IMPORT OSRunning ; External references
IMPORT OSPrioCur
IMPORT OSPrioHighRdy
IMPORT OSTCBCur
IMPORT OSTCBHighRdy
IMPORT OSIntNesting
IMPORT OSIntExit
IMPORT OSTaskSwHook
EXPORT OSStartHighRdy
EXPORT OSCtxSw
EXPORT OSIntCtxSw
EXPORT OS_CPU_SR_Save ; Functions declared in this file
EXPORT OS_CPU_SR_Restore
EXPORT PendSV_Handler
NVIC_INT_CTRL EQU 0xE000ED04 ; 中断控制寄存器
NVIC_SYSPRI2 EQU 0xE000ED22 ; 系统优先级寄存器(2)
NVIC_PENDSV_PRI EQU 0xFFFF ; PendSV中断和系统节拍中断
; (都为最低,0xff).
NVIC_PENDSVSET EQU 0x10000000 ; 触发软件中断的值.
PRESERVE8
AREA |.text|, CODE, READONLY
THUMB
;********************************************************************************************************
; CRITICAL SECTION METHOD 3 FUNCTIONS
;
; Description: Disable/Enable interrupts by preserving the state of interrupts. Generally speaking you
; would store the state of the interrupt disable flag in the local variable 'cpu_sr' and then
; disable interrupts. 'cpu_sr' is allocated in all of uC/OS-II's functions that need to
; disable interrupts. You would restore the interrupt disable state by copying back 'cpu_sr'
; into the CPU's status register.
;
; Prototypes : OS_CPU_SR OS_CPU_SR_Save(void);
; void OS_CPU_SR_Restore(OS_CPU_SR cpu_sr);
;
;
; Note(s) : 1) These functions are used in general like this:
;
; void Task (void *p_arg)
; {
; #if OS_CRITICAL_METHOD == 3 /* Allocate storage for CPU status register */
; OS_CPU_SR cpu_sr;
; #endif
;
; :
; :
; OS_ENTER_CRITICAL(); /* cpu_sr = OS_CPU_SaveSR(); */
; :
; :
; OS_EXIT_CRITICAL(); /* OS_CPU_RestoreSR(cpu_sr); */
; :
; :
; }
;********************************************************************************************************
OS_CPU_SR_Save
MRS R0, PRIMASK ;读取PRIMASK到R0,R0为返回值
CPSID I ;PRIMASK=1,关中断(NMI和硬件FAULT可以响应)
BX LR ;返回
OS_CPU_SR_Restore
MSR PRIMASK, R0 ;读取R0到PRIMASK中,R0为参数
BX LR ;返回
;/**************************************************************************************
;* 函数名称: OSStartHighRdy
;*
;* 功能描述: 使用调度器运行第一个任务
;*
;* 参 数: None
;*
;* 返 回 值: None
;**************************************************************************************/
OSStartHighRdy
LDR R4, =NVIC_SYSPRI2 ; set the PendSV exception priority
LDR R5, =NVIC_PENDSV_PRI
STR R5, [R4]
MOV R4, #0 ; set the PSP to 0 for initial context switch call
MSR PSP, R4
LDR R4, =OSRunning ; OSRunning = TRUE
MOV R5, #1
STRB R5, [R4]
;切换到最高优先级的任务
LDR R4, =NVIC_INT_CTRL ;rigger the PendSV exception (causes context switch)
LDR R5, =NVIC_PENDSVSET
STR R5, [R4]
CPSIE I ;enable interrupts at processor level
OSStartHang
B OSStartHang ;should never get here
;/**************************************************************************************
;* 函数名称: OSCtxSw
;*
;* 功能描述: 任务级上下文切换
;*
;* 参 数: None
;*
;* 返 回 值: None
;***************************************************************************************/
OSCtxSw
PUSH {R4, R5}
LDR R4, =NVIC_INT_CTRL ;触发PendSV异常 (causes context switch)
LDR R5, =NVIC_PENDSVSET
STR R5, [R4]
POP {R4, R5}
BX LR
;/**************************************************************************************
;* 函数名称: OSIntCtxSw
;*
;* 功能描述: 中断级任务切换
;*
;* 参 数: None
;*
;* 返 回 值: None
;***************************************************************************************/
OSIntCtxSw
PUSH {R4, R5}
LDR R4, =NVIC_INT_CTRL ;触发PendSV异常 (causes context switch)
LDR R5, =NVIC_PENDSVSET
STR R5, [R4]
POP {R4, R5}
BX LR
NOP
;/**************************************************************************************
;* 函数名称: OSPendSV
;*
;* 功能描述: OSPendSV is used to cause a context switch.
;*
;* 参 数: None
;*
;* 返 回 值: None
;***************************************************************************************/
PendSV_Handler
CPSID I ; Prevent interruption during context switch
MRS R0, PSP ; PSP is process stack pointer 如果在用PSP堆栈,则可以忽略保存寄存器,参考CM3权威中的双堆栈-白菜注
CBZ R0, PendSV_Handler_Nosave ; Skip register save the first time
;Is the task using the FPU context? If so, push high vfp registers.
TST R14, #0x10
IT EQ
VSTMDBEQ R0!, {S16-S31}
SUBS R0, R0, #0x20 ; Save remaining regs r4-11 on process stack
STM R0, {R4-R11}
LDR R1, =OSTCBCur ; OSTCBCur->OSTCBStkPtr = SP;
LDR R1, [R1]
STR R0, [R1] ; R0 is SP of process being switched out
; At this point, entire context of process has been saved
PendSV_Handler_Nosave
PUSH {R14} ; Save LR exc_return value
LDR R0, =OSTaskSwHook ; OSTaskSwHook();
BLX R0
POP {R14}
LDR R0, =OSPrioCur ; OSPrioCur = OSPrioHighRdy;
LDR R1, =OSPrioHighRdy
LDRB R2, [R1]
STRB R2, [R0]
LDR R0, =OSTCBCur ; OSTCBCur = OSTCBHighRdy;
LDR R1, =OSTCBHighRdy
LDR R2, [R1]
STR R2, [R0]
LDR R0, [R2] ; R0 is new process SP; SP = OSTCBHighRdy->OSTCBStkPtr;
LDM R0, {R4-R11} ; Restore r4-11 from new process stack
ADDS R0, R0, #0x20
;Is the task using the FPU context? If so, push high vfp registers.
TST R14, #0x10
IT EQ
VLDMIAEQ R0!, {S16-S31}
MSR PSP, R0 ; Load PSP with new process SP
ORR LR, LR, #0x04 ; Ensure exception return uses process stack
CPSIE I
BX LR ; Exception return will restore remaining context
NOP
END
|
; A302338: a(n) = 3*n + 2^v(n) where v(n) denotes the 2-adic valuation of n.
; 4,8,10,16,16,20,22,32,28,32,34,40,40,44,46,64,52,56,58,64,64,68,70,80,76,80,82,88,88,92,94,128,100,104,106,112,112,116,118,128,124,128,130,136,136,140,142,160,148,152,154,160,160,164,166,176,172,176,178,184,184,188,190,256,196,200,202,208,208,212,214,224,220,224,226,232,232,236,238,256,244,248,250,256,256,260,262,272,268,272,274,280,280,284,286,320,292,296,298,304,304,308,310,320,316,320,322,328,328,332,334,352,340,344,346,352,352,356,358,368,364,368,370,376,376,380,382,512,388,392,394,400,400,404,406,416,412,416,418,424,424,428,430,448,436,440,442,448,448,452,454,464,460,464,466,472,472,476,478,512,484,488,490,496,496,500,502,512,508,512,514,520,520,524,526,544,532,536,538,544,544,548,550,560,556,560,562,568,568,572,574,640,580,584,586,592,592,596,598,608,604,608,610,616,616,620,622,640,628,632,634,640,640,644,646,656,652,656,658,664,664,668,670,704,676,680,682,688,688,692,694,704,700,704,706,712,712,716,718,736,724,728,730,736,736,740,742,752,748,752
mov $1,256
mov $3,$0
add $0,1
gcd $1,$0
add $1,3
mov $2,$3
mul $2,3
add $1,$2
|
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma
// de Barcelona (UAB).
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#include "carla/client/World.h"
#include "carla/Logging.h"
#include "carla/client/Actor.h"
#include "carla/client/ActorBlueprint.h"
#include "carla/client/ActorList.h"
#include "carla/client/detail/Simulator.h"
#include <exception>
namespace carla {
namespace client {
SharedPtr<Map> World::GetMap() const {
return _episode.Lock()->GetCurrentMap();
}
SharedPtr<BlueprintLibrary> World::GetBlueprintLibrary() const {
return _episode.Lock()->GetBlueprintLibrary();
}
boost::optional<geom::Location> World::GetRandomLocationFromNavigation() const {
return _episode.Lock()->GetRandomLocationFromNavigation();
}
SharedPtr<Actor> World::GetSpectator() const {
return _episode.Lock()->GetSpectator();
}
rpc::EpisodeSettings World::GetSettings() const {
return _episode.Lock()->GetEpisodeSettings();
}
uint64_t World::ApplySettings(const rpc::EpisodeSettings &settings) {
return _episode.Lock()->SetEpisodeSettings(settings);
}
uint32_t World::SpawnDynamicMesh(const std::vector<geom::Vector3D> &triangles, std::string material, uint8_t semantic_segmentation_label) {
return _episode.Lock()->SpawnDynamicMesh(triangles, material, semantic_segmentation_label);
}
uint32_t World::SpawnDynamicTileMesh(const geom::Vector3D& bounds_min, const geom::Vector3D& bounds_max, const std::vector<uint8_t>& data, uint8_t semantic_segmentation_label) {
return _episode.Lock()->SpawnDynamicTileMesh(bounds_min, bounds_max, data, semantic_segmentation_label);
}
bool World::DestroyDynamicMesh(uint32_t id) {
return _episode.Lock()->DestroyDynamicMesh(id);
}
rpc::WeatherParameters World::GetWeather() const {
return _episode.Lock()->GetWeatherParameters();
}
void World::SetWeather(const rpc::WeatherParameters &weather) {
_episode.Lock()->SetWeatherParameters(weather);
}
WorldSnapshot World::GetSnapshot() const {
return _episode.Lock()->GetWorldSnapshot();
}
SharedPtr<Actor> World::GetActor(ActorId id) const {
auto simulator = _episode.Lock();
auto description = simulator->GetActorById(id);
return description.has_value() ?
simulator->MakeActor(std::move(*description)) :
nullptr;
}
SharedPtr<ActorList> World::GetActors() const {
return SharedPtr<ActorList>{new ActorList{
_episode,
_episode.Lock()->GetAllTheActorsInTheEpisode()}};
}
SharedPtr<ActorList> World::GetActors(const std::vector<ActorId> &actor_ids) const {
return SharedPtr<ActorList>{new ActorList{
_episode,
_episode.Lock()->GetActorsById(actor_ids)}};
}
SharedPtr<Actor> World::SpawnActor(
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent_actor,
rpc::AttachmentType attachment_type) {
return _episode.Lock()->SpawnActor(blueprint, transform, parent_actor, attachment_type);
}
SharedPtr<Actor> World::TrySpawnActor(
const ActorBlueprint &blueprint,
const geom::Transform &transform,
Actor *parent_actor,
rpc::AttachmentType attachment_type) noexcept {
try {
return SpawnActor(blueprint, transform, parent_actor, attachment_type);
} catch (const std::exception &) {
return nullptr;
}
}
WorldSnapshot World::WaitForTick(time_duration timeout) const {
return _episode.Lock()->WaitForTick(timeout);
}
size_t World::OnTick(std::function<void(WorldSnapshot)> callback) {
return _episode.Lock()->RegisterOnTickEvent(std::move(callback));
}
void World::RemoveOnTick(size_t callback_id) {
_episode.Lock()->RemoveOnTickEvent(callback_id);
}
uint64_t World::Tick(time_duration timeout) {
return _episode.Lock()->Tick(timeout);
}
void World::SetPedestriansCrossFactor(float percentage) {
_episode.Lock()->SetPedestriansCrossFactor(percentage);
}
} // namespace client
} // namespace carla
|
; A029609: Central numbers in the (2,3)-Pascal triangle A029600.
; Submitted by Jon Maiga
; 1,5,15,50,175,630,2310,8580,32175,121550,461890,1763580,6760390,26001500,100291500,387793800,1502700975,5834015550,22687838250,88363159500,344616322050,1345644686100,5260247409300,20583576819000,80619009207750,316026516094380,1239796332370260,4867348564120280,19121726501901100,75168166248852600,295661453912153560,1163570883138152720,4581560352356476335,18048571085040664350,71132603688101441850,280465694541657113580,1106281350692091948010,4365326410839065524580,17231551621733153386500
mov $1,$0
mul $0,2
bin $0,$1
mul $0,5
add $0,1
dif $0,2
sub $0,3
div $0,2
add $0,1
|
SECTION code_driver
SECTION code_driver_terminal_output
PUBLIC console_01_output_char_proc_move_right
EXTERN console_01_output_char_proc_move_down
EXTERN console_01_output_char_proc_move_down_check_y
console_01_output_char_proc_move_right:
; move right, wrap, snap to window
;
; enter : e = x coord
; d = y coord
;
; c = window.width
; b = window.height
;
; exit : e = new x coord
; d = new y coord
;
; uses : af, de
ld a,e
inc a
jr z, x_is_large
inc e
cp c
jr nc, x_is_large ; if x >= window.width
ld a,d
jp console_01_output_char_proc_move_down_check_y
x_is_large:
ld e,0
jp console_01_output_char_proc_move_down
|
; ===============================================================
; Dec 2013
; ===============================================================
;
; char *strchr(const char *s, int c)
;
; Return ptr to first occurrence of c in string s or NULL
; if c is not found.
;
; ===============================================================
SECTION code_clib
SECTION code_string
PUBLIC asm_strchr
EXTERN error_zc
asm_strchr:
; enter : c = char c
; hl = char *s
;
; exit : c = char c
;
; found
;
; carry reset
; hl = ptr to c
;
; not found
;
; carry set
; hl = 0
;
; uses : af, hl
loop:
ld a,(hl)
cp c
ret Z
inc hl
or a ; end of string?
jr NZ,loop
jp error_zc
|
/***************************************************************************************/
/* Tabulate the tensor for the local element contribution */
void SpecificFEM::Tabulate_Tensor(const CLASS_geom_Gamma_embedded_in_Omega_restricted_to_Gamma& Mesh)
{
const unsigned int NQ = 5;
// Compute element tensor using quadrature
// Loop quadrature points for integral
for (unsigned int j = 0; j < COL_NB; j++)
{
for (unsigned int i = j; i < ROW_NB; i++)
{
double A0_value = 0.0; // initialize
for (unsigned int qp = 0; qp < NQ; qp++)
{
const double integrand_0 = (*M_Space_phi_restricted_to_Gamma->Func_f_Value)[j][qp].a*(*M_Space_phi_restricted_to_Gamma->Func_f_Value)[i][qp].a;
A0_value += integrand_0 * Mesh.Map_Det_Jac_w_Weight[qp].a;
}
FE_Tensor_0[j*ROW_NB + i] = A0_value;
}
}
// Copy the lower triangular entries to the upper triangular part (by symmetry)
for (unsigned int j = 0; j < COL_NB; j++)
{
for (unsigned int i = j+1; i < ROW_NB; i++)
{
FE_Tensor_0[i*ROW_NB + j] = FE_Tensor_0[j*ROW_NB + i];
}
}
}
/***************************************************************************************/
|
bootblock.o: 文件格式 elf32-i386
Disassembly of section .text:
00007c00 <start>:
# with %cs=0 %ip=7c00.
.code16 # Assemble for 16-bit mode
.globl start
start:
cli # BIOS enabled interrupts; disable
7c00: fa cli
# Zero data segment registers DS, ES, and SS.
xorw %ax,%ax # Set %ax to zero
7c01: 31 c0 xor %eax,%eax
movw %ax,%ds # -> Data Segment
7c03: 8e d8 mov %eax,%ds
movw %ax,%es # -> Extra Segment
7c05: 8e c0 mov %eax,%es
movw %ax,%ss # -> Stack Segment
7c07: 8e d0 mov %eax,%ss
00007c09 <seta20.1>:
# Physical address line A20 is tied to zero so that the first PCs
# with 2 MB would run software that assumed 1 MB. Undo that.
seta20.1:
inb $0x64,%al # Wait for not busy
7c09: e4 64 in $0x64,%al
testb $0x2,%al
7c0b: a8 02 test $0x2,%al
jnz seta20.1
7c0d: 75 fa jne 7c09 <seta20.1>
movb $0xd1,%al # 0xd1 -> port 0x64
7c0f: b0 d1 mov $0xd1,%al
outb %al,$0x64
7c11: e6 64 out %al,$0x64
00007c13 <seta20.2>:
seta20.2:
inb $0x64,%al # Wait for not busy
7c13: e4 64 in $0x64,%al
testb $0x2,%al
7c15: a8 02 test $0x2,%al
jnz seta20.2
7c17: 75 fa jne 7c13 <seta20.2>
movb $0xdf,%al # 0xdf -> port 0x60
7c19: b0 df mov $0xdf,%al
outb %al,$0x60
7c1b: e6 60 out %al,$0x60
# Switch from real to protected mode. Use a bootstrap GDT that makes
# virtual addresses map directly to physical addresses so that the
# effective memory map doesn't change during the transition.
lgdt gdtdesc
7c1d: 0f 01 16 lgdtl (%esi)
7c20: 78 7c js 7c9e <readsect+0x12>
movl %cr0, %eax
7c22: 0f 20 c0 mov %cr0,%eax
orl $CR0_PE, %eax
7c25: 66 83 c8 01 or $0x1,%ax
movl %eax, %cr0
7c29: 0f 22 c0 mov %eax,%cr0
//PAGEBREAK!
# Complete the transition to 32-bit protected mode by using a long jmp
# to reload %cs and %eip. The segment descriptors are set up with no
# translation, so that the mapping is still the identity mapping.
ljmp $(SEG_KCODE<<3), $start32
7c2c: ea .byte 0xea
7c2d: 31 7c 08 00 xor %edi,0x0(%eax,%ecx,1)
00007c31 <start32>:
.code32 # Tell assembler to generate 32-bit code now.
start32:
# Set up the protected-mode data segment registers
movw $(SEG_KDATA<<3), %ax # Our data segment selector
7c31: 66 b8 10 00 mov $0x10,%ax
movw %ax, %ds # -> DS: Data Segment
7c35: 8e d8 mov %eax,%ds
movw %ax, %es # -> ES: Extra Segment
7c37: 8e c0 mov %eax,%es
movw %ax, %ss # -> SS: Stack Segment
7c39: 8e d0 mov %eax,%ss
movw $0, %ax # Zero segments not ready for use
7c3b: 66 b8 00 00 mov $0x0,%ax
movw %ax, %fs # -> FS
7c3f: 8e e0 mov %eax,%fs
movw %ax, %gs # -> GS
7c41: 8e e8 mov %eax,%gs
# Set up the stack pointer and call into C.
movl $start, %esp
7c43: bc 00 7c 00 00 mov $0x7c00,%esp
call bootmain
7c48: e8 f0 00 00 00 call 7d3d <bootmain>
# If bootmain returns (it shouldn't), trigger a Bochs
# breakpoint if running under Bochs, then loop.
movw $0x8a00, %ax # 0x8a00 -> port 0x8a00
7c4d: 66 b8 00 8a mov $0x8a00,%ax
movw %ax, %dx
7c51: 66 89 c2 mov %ax,%dx
outw %ax, %dx
7c54: 66 ef out %ax,(%dx)
movw $0x8ae0, %ax # 0x8ae0 -> port 0x8a00
7c56: 66 b8 e0 8a mov $0x8ae0,%ax
outw %ax, %dx
7c5a: 66 ef out %ax,(%dx)
00007c5c <spin>:
spin:
jmp spin
7c5c: eb fe jmp 7c5c <spin>
7c5e: 66 90 xchg %ax,%ax
00007c60 <gdt>:
...
7c68: ff (bad)
7c69: ff 00 incl (%eax)
7c6b: 00 00 add %al,(%eax)
7c6d: 9a cf 00 ff ff 00 00 lcall $0x0,$0xffff00cf
7c74: 00 .byte 0x0
7c75: 92 xchg %eax,%edx
7c76: cf iret
...
00007c78 <gdtdesc>:
7c78: 17 pop %ss
7c79: 00 60 7c add %ah,0x7c(%eax)
...
00007c7e <waitdisk>:
static inline uchar
inb(ushort port)
{
uchar data;
asm volatile("in %1,%0" : "=a" (data) : "d" (port));
7c7e: ba f7 01 00 00 mov $0x1f7,%edx
7c83: ec in (%dx),%al
void
waitdisk(void)
{
// Wait for disk ready.
while((inb(0x1F7) & 0xC0) != 0x40)
7c84: 83 e0 c0 and $0xffffffc0,%eax
7c87: 3c 40 cmp $0x40,%al
7c89: 75 f8 jne 7c83 <waitdisk+0x5>
;
}
7c8b: c3 ret
00007c8c <readsect>:
// Read a single sector at offset into dst.
void
readsect(void *dst, uint offset)
{
7c8c: 55 push %ebp
7c8d: 89 e5 mov %esp,%ebp
7c8f: 57 push %edi
7c90: 53 push %ebx
7c91: 8b 5d 0c mov 0xc(%ebp),%ebx
// Issue command.
waitdisk();
7c94: e8 e5 ff ff ff call 7c7e <waitdisk>
}
static inline void
outb(ushort port, uchar data)
{
asm volatile("out %0,%1" : : "a" (data), "d" (port));
7c99: b8 01 00 00 00 mov $0x1,%eax
7c9e: ba f2 01 00 00 mov $0x1f2,%edx
7ca3: ee out %al,(%dx)
7ca4: ba f3 01 00 00 mov $0x1f3,%edx
7ca9: 89 d8 mov %ebx,%eax
7cab: ee out %al,(%dx)
outb(0x1F2, 1); // count = 1
outb(0x1F3, offset);
outb(0x1F4, offset >> 8);
7cac: 89 d8 mov %ebx,%eax
7cae: c1 e8 08 shr $0x8,%eax
7cb1: ba f4 01 00 00 mov $0x1f4,%edx
7cb6: ee out %al,(%dx)
outb(0x1F5, offset >> 16);
7cb7: 89 d8 mov %ebx,%eax
7cb9: c1 e8 10 shr $0x10,%eax
7cbc: ba f5 01 00 00 mov $0x1f5,%edx
7cc1: ee out %al,(%dx)
outb(0x1F6, (offset >> 24) | 0xE0);
7cc2: 89 d8 mov %ebx,%eax
7cc4: c1 e8 18 shr $0x18,%eax
7cc7: 83 c8 e0 or $0xffffffe0,%eax
7cca: ba f6 01 00 00 mov $0x1f6,%edx
7ccf: ee out %al,(%dx)
7cd0: b8 20 00 00 00 mov $0x20,%eax
7cd5: ba f7 01 00 00 mov $0x1f7,%edx
7cda: ee out %al,(%dx)
outb(0x1F7, 0x20); // cmd 0x20 - read sectors
// Read data.
waitdisk();
7cdb: e8 9e ff ff ff call 7c7e <waitdisk>
asm volatile("cld; rep insl" :
7ce0: 8b 7d 08 mov 0x8(%ebp),%edi
7ce3: b9 80 00 00 00 mov $0x80,%ecx
7ce8: ba f0 01 00 00 mov $0x1f0,%edx
7ced: fc cld
7cee: f3 6d rep insl (%dx),%es:(%edi)
insl(0x1F0, dst, SECTSIZE/4);
}
7cf0: 5b pop %ebx
7cf1: 5f pop %edi
7cf2: 5d pop %ebp
7cf3: c3 ret
00007cf4 <readseg>:
// Read 'count' bytes at 'offset' from kernel into physical address 'pa'.
// Might copy more than asked.
void
readseg(uchar* pa, uint count, uint offset)
{
7cf4: 55 push %ebp
7cf5: 89 e5 mov %esp,%ebp
7cf7: 57 push %edi
7cf8: 56 push %esi
7cf9: 53 push %ebx
7cfa: 83 ec 0c sub $0xc,%esp
7cfd: 8b 5d 08 mov 0x8(%ebp),%ebx
7d00: 8b 75 10 mov 0x10(%ebp),%esi
uchar* epa;
epa = pa + count;
7d03: 89 df mov %ebx,%edi
7d05: 03 7d 0c add 0xc(%ebp),%edi
// Round down to sector boundary.
pa -= offset % SECTSIZE;
7d08: 89 f0 mov %esi,%eax
7d0a: 25 ff 01 00 00 and $0x1ff,%eax
7d0f: 29 c3 sub %eax,%ebx
// Translate from bytes to sectors; kernel starts at sector 1.
offset = (offset / SECTSIZE) + 1;
7d11: c1 ee 09 shr $0x9,%esi
7d14: 83 c6 01 add $0x1,%esi
// If this is too slow, we could read lots of sectors at a time.
// We'd write more to memory than asked, but it doesn't matter --
// we load in increasing order.
for(; pa < epa; pa += SECTSIZE, offset++)
7d17: 39 df cmp %ebx,%edi
7d19: 76 1a jbe 7d35 <readseg+0x41>
readsect(pa, offset);
7d1b: 83 ec 08 sub $0x8,%esp
7d1e: 56 push %esi
7d1f: 53 push %ebx
7d20: e8 67 ff ff ff call 7c8c <readsect>
for(; pa < epa; pa += SECTSIZE, offset++)
7d25: 81 c3 00 02 00 00 add $0x200,%ebx
7d2b: 83 c6 01 add $0x1,%esi
7d2e: 83 c4 10 add $0x10,%esp
7d31: 39 df cmp %ebx,%edi
7d33: 77 e6 ja 7d1b <readseg+0x27>
}
7d35: 8d 65 f4 lea -0xc(%ebp),%esp
7d38: 5b pop %ebx
7d39: 5e pop %esi
7d3a: 5f pop %edi
7d3b: 5d pop %ebp
7d3c: c3 ret
00007d3d <bootmain>:
{
7d3d: 55 push %ebp
7d3e: 89 e5 mov %esp,%ebp
7d40: 57 push %edi
7d41: 56 push %esi
7d42: 53 push %ebx
7d43: 83 ec 10 sub $0x10,%esp
readseg((uchar*)elf, 4096, 0);
7d46: 6a 00 push $0x0
7d48: 68 00 10 00 00 push $0x1000
7d4d: 68 00 00 01 00 push $0x10000
7d52: e8 9d ff ff ff call 7cf4 <readseg>
if(elf->magic != ELF_MAGIC)
7d57: 83 c4 10 add $0x10,%esp
7d5a: 81 3d 00 00 01 00 7f cmpl $0x464c457f,0x10000
7d61: 45 4c 46
7d64: 75 21 jne 7d87 <bootmain+0x4a>
ph = (struct proghdr*)((uchar*)elf + elf->phoff);
7d66: a1 1c 00 01 00 mov 0x1001c,%eax
7d6b: 8d 98 00 00 01 00 lea 0x10000(%eax),%ebx
eph = ph + elf->phnum;
7d71: 0f b7 35 2c 00 01 00 movzwl 0x1002c,%esi
7d78: c1 e6 05 shl $0x5,%esi
7d7b: 01 de add %ebx,%esi
for(; ph < eph; ph++){
7d7d: 39 f3 cmp %esi,%ebx
7d7f: 72 15 jb 7d96 <bootmain+0x59>
entry();
7d81: ff 15 18 00 01 00 call *0x10018
}
7d87: 8d 65 f4 lea -0xc(%ebp),%esp
7d8a: 5b pop %ebx
7d8b: 5e pop %esi
7d8c: 5f pop %edi
7d8d: 5d pop %ebp
7d8e: c3 ret
for(; ph < eph; ph++){
7d8f: 83 c3 20 add $0x20,%ebx
7d92: 39 de cmp %ebx,%esi
7d94: 76 eb jbe 7d81 <bootmain+0x44>
pa = (uchar*)ph->paddr;
7d96: 8b 7b 0c mov 0xc(%ebx),%edi
readseg(pa, ph->filesz, ph->off);
7d99: 83 ec 04 sub $0x4,%esp
7d9c: ff 73 04 pushl 0x4(%ebx)
7d9f: ff 73 10 pushl 0x10(%ebx)
7da2: 57 push %edi
7da3: e8 4c ff ff ff call 7cf4 <readseg>
if(ph->memsz > ph->filesz)
7da8: 8b 4b 14 mov 0x14(%ebx),%ecx
7dab: 8b 43 10 mov 0x10(%ebx),%eax
7dae: 83 c4 10 add $0x10,%esp
7db1: 39 c1 cmp %eax,%ecx
7db3: 76 da jbe 7d8f <bootmain+0x52>
stosb(pa + ph->filesz, 0, ph->memsz - ph->filesz);
7db5: 01 c7 add %eax,%edi
7db7: 29 c1 sub %eax,%ecx
}
static inline void
stosb(void *addr, int data, int cnt)
{
asm volatile("cld; rep stosb" :
7db9: b8 00 00 00 00 mov $0x0,%eax
7dbe: fc cld
7dbf: f3 aa rep stos %al,%es:(%edi)
7dc1: eb cc jmp 7d8f <bootmain+0x52>
|
0,
0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0
|
; Copyright (c) 2009-2012, Michael Alyn Miller <malyn@strangeGizmo.com>.
; 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
; unmodified, this list of conditions, and the following disclaimer.
; 2. Redistributions in binary form must reproduce the above copyright notice,
; this list of conditions and the following disclaimer in the documentation
; and/or other materials provided with the distribution.
; 3. Neither the name of Michael Alyn Miller nor the names of the contributors
; to this software may be used to endorse or promote products derived from
; this software without specific prior written permission.
;
; THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS "AS IS" AND ANY
; EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
; WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
; DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY
; DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
; (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
; ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
; (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
; THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
; ======================================================================
; MFORTH Version Information
; ======================================================================
MFORTH_MAJOR .EQU 1
MFORTH_MINOR .EQU 1
;MFORTH_COMMIT .EQU Supplied on the TASM command line.
; ======================================================================
; MFORTH Register Usage
; ======================================================================
;
; HL - Word Pointer (W); only used by the Address Interpreter, available
; for general use by CODE words.
; DE - Instruction Pointer (IP); must be preserved with SAVEDE/RESTOREDE.
; BC - Return Stack Pointer (RSP); must be preserved if used (usually by
; pushing BC onto the stack). B always contains the TASK page.
; SP - Parameter Stack Pointer (PSP).
; A - Unused.
; ======================================================================
; MFORTH Memory Maps
; ======================================================================
;
; Model 100 Memory Map:
;
; +--------------------------------+ 0000h (32k) or 2000h (24k)
; | Files, BASIC variables, etc. |
; +--------------------------------+ [FRETOP]
; | |
; | Free Memory |
; | |
; +--------------------------------+ SP
; | Stack |
; +--------------------------------+ [STKTOP]
; | System variables |
; +--------------------------------+ FFFFh
;
;
; MFORTH Memory Map:
;
; +--------------------------------+ 0000h (32k) or 2000h (24k)
; | Files, BASIC variables, etc. |
; +--------------------------------+ [FRETOP] aka [TICKTIB]
; | Terminal Input Buffer |
; +--------------------------------+ [TICKTIB] + TIBSIZE aka [DP] aka HERE
; | Dictionary |
; | (see below for temp regions) |
; | vvvv |
; | |
; | |
; | ^^^^ |
; | Additional Tasks (256b each) |
; +--------------------------------+ xx00h (first whole page below BOPSTK)
; | Initial MFORTH Task (Task #0) |
; +--------------------------------+ [BOPSTK]
; | Original Stack (unused by us) |
; +--------------------------------+ [STKTOP]
; | System variables |
; +--------------------------------+ FFFFh
;
;
; Transient Regions (based on HERE):
;
; +--------------------------------+ [TICKTIB] + TIBSIZE aka [DP] aka HERE
; | Empty; space for the header and|
; | name of the next definition so |
; | that CREATE can reference the |
; | WORD buffer and not clobber it.|
; +--------------------------------+ [DP] + WORDOFFSET
; | Buffer used by WORD |
; | vvvv |
; | ^^^^ |
; | Buffer used by HLD |
; +--------------------------------+ [DP] + SQOFFSET aka [DP] + HLDEND
; | S" buffer |
; +--------------------------------+ [DP] + PADOFFSET
; | PAD buffer for Task #0 |
; +--------------------------------+ [DP] + PADOFFSET + tasknum*PADSIZE
; | Additional per-task PAD buffers|
; | vvvv |
; +--------------------------------+
;
;
; Task Page (at xx00h in high memory):
;
; +--------------------------------+ xx00h
; | User Variables |
; +--------------------------------+ xx40h
; | ^^^^ |
; | Return Stack |
; +--------------------------------+ xx7Fh
; | Return/Param Stack Guard Cell |
; +--------------------------------+ xx81h
; | ^^^^ |
; | Parameter Stack |
; +--------------------------------+ xxFFh
;
;
; Dictionary Header:
;
; The MFORTH dictionary uses the layout described by Robert L. Smith
; in his Forth Dimensions I/5 article titled "A Modest Proposal for
; Dictionary Headers".
;
; The 00h byte is called the Name Field Address in MFORTH, even though
; it only points to the name count and flags. The Link Field Address
; points to the Name Field Address of the preceding definition.
;
; The Profiler Execution Count (the dotted cell at 03h) is only used
; when the profiler is enabled at build time. That cell is not used,
; nor is it even allocated (the fixed size of the dictionary header is
; only three bytes, in other words) when the profiler is disabled. The
; Profiler Execution Count stores the number of times that the word
; was executed by NEXT when the PROFILING variable is non-zero.
;
; The header below is for the word DUP; note that the word name is
; stored in reverse order in memory.
;
; +--------------------------------+ -03h
; | 1 | 'P' |
; +--------------------------------+ -02h
; | 0 | 'U' |
; +--------------------------------+ -01h
; | 0 | 'D' |
; +--------------------------------+ 00h
; | P | S | Count |
; +--------------------------------+ 01h
; | Link |
; | Field |
; +--------------------------------+ 03h
; . Profiler .
; . Execution Count .
; +--------------------------------+ 03h/05h
; | Code |
; | Field |
; | (JMP $xxxx) |
; +--------------------------------+ 06h/08h
; . Parameter .
; . Field .
; . . . . . . . . . . . . . . . . .
;
;
; Word List:
;
; An MFORTH wid is a pointer to a word list (HERE, in the case of word
; lists created by WORDLIST). A word list is a single cell that is
; the equivalent of LATEST for that word list. The value at the word
; list is updated as new words are added to the word list.
; ======================================================================
; Undocumented 8085 Opcodes
; ======================================================================
; INSTR ARGS OPCODE BYTES MOD CLASS
.ADDINSTR DSUB "" 08 1 NOP 1
.ADDINSTR LDEH * 28 2 NOP 1
.ADDINSTR LDES * 38 2 NOP 1
.ADDINSTR LHLX "" ED 1 NOP 1
.ADDINSTR RDEL "" 18 1 NOP 1
.ADDINSTR SHLX "" D9 1 NOP 1
; ======================================================================
; Model 100/102 Constants
; ======================================================================
FRETOP: .EQU 0FBB6h ; Beginning of free space on the machine
; (after all files, BASIC vars, etc.)
STKTOP: .EQU 0F678h ; Top of the system stack; system stack
; grows downward, although we don't
; use this stack for anything.
ALTBGN: .EQU 0FCC0h ; Beginning of the Alternate LCD buffer
ALTEND: .EQU 0FDFFh ; End of the Alternate LCD buffer
STACKGUARD: .EQU 076h ; The guard value used to see if a Task
; has over-/under-flown a stack. $76
; is "HLT" just in case someone tries
; to execute the stack pointer.
; ======================================================================
; MFORTH Dictionary Constants
; ======================================================================
NFASZ: .EQU 1 ; Size of the Name Field.
#DEFINE INXNFATOLFA(r) INX r
LFASZ: .EQU 2 ; Size of the Link Field.
#IFNDEF PROFILER
NFATOCFASZ: .EQU NFASZ+LFASZ
#DEFINE INXNFATOCFA(r) INX r\ INX r\ INX r
#ELSE
NFATOPECSZ: .EQU NFASZ+LFASZ
PECSZ: .EQU 2 ; Size of the Profiler Execution Count.
NFATOCFASZ: .EQU NFASZ+LFASZ+PECSZ
#DEFINE INXNFATOCFA(r) INX r\ INX r\ INX r\ INX r\ INX r
#ENDIF
CFASZ: .EQU 3 ; Size of the Code Field.
#DEFINE INXCFATOPFA(r) INX r\ INX r\ INX r
; ======================================================================
; MFORTH Constants
; ======================================================================
TIBSIZE: .EQU 80 ; Length of the Terminal Input Buffer.
WORDOFFSET: .EQU 64 ; Offset from HERE to WORD buffer.
WORDSIZE: .EQU 258 ; Size of WORD buffer.
HLDEND: .EQU WORDOFFSET+WORDSIZE ; End (and thus, start) of HLD.
SQOFFSET: .EQU HLDEND ; Offset from HERE to S" buffer.
SQSIZE: .EQU 80 ; Size of S" buffer.
PADOFFSET: .EQU SQOFFSET+SQSIZE ; Offset from HERE to first PAD buffer.
PADSIZE: .EQU 256 ; Size of each task's PAD buffer.
MAXICBS: .EQU 8 ; Maximum number of active input sources.
MAXFCBS: .EQU 8 ; Maximum number of files open at one time.
MAXSOES: .EQU 8 ; Max. number of word lists in the search order.
; ======================================================================
; Global variables (stored in the Alternate LCD buffer)
; Max of 320 bytes.
;
; OPON and the variables used by OPON take up the first 23 bytes.
; That leaves 297 bytes remaining.
;
; These globals are shared across all of the active tasks, so they must
; either be safe (not used from multiple tasks at a time; DP is such a
; variable as we atomically add new dictionary entries without an
; intervening PAUSE) or be defined in the manual as not being usable from
; multiple tasks. All of the terminal input variables fall into this
; category as we specifically state that only a single terminal/operator
; is supported.
; ======================================================================
OPON .EQU ALTBGN + 0
#IF (OPONLEN > 16)
#ECHO "\t*** ERROR: OPON is too large; Global Variables expect OPONLEN<=16 ***\n"
#ENDIF
HOLDH: .EQU ALTBGN + 16
HOLDD: .EQU ALTBGN + 18
INTH: .EQU ALTBGN + 20
INTD: .EQU ALTBGN + 22
DP: .EQU ALTBGN + 24 ; Data Pointer.
BOPSTK: .EQU ALTBGN + 26 ; Initial value of SP on entry to MFORTH.
TICKCURRENT: .EQU ALTBGN + 28 ; Pointer to the compilation word list.
TICKSTATE: .EQU ALTBGN + 30 ; Compilation-state flag.
TICKTIB: .EQU ALTBGN + 32 ; Terminal Input Buffer pointer.
TICKHLD: .EQU ALTBGN + 34 ; Pictured Numeric Output hold pointer.
TICKNUMTASKS:.EQU ALTBGN + 36 ; Number of tasks
TICKFIRSTTASK:.EQU ALTBGN + 38 ; Address of the first task (always XX00)
TICKNUMUSERVARS:.EQU ALTBGN+ 40 ; Number of USER variables
SAVED: .EQU ALTBGN + 42 ; DE is saved here when used as a temporary.
TICKPREVLEAVE:.EQU ALTBGN + 44 ; Pointer to the previous LEAVE in a DO..LOOP.
TICKPREVENDB:.EQU ALTBGN + 46 ; Pointer to the previous ?ENDB in a FORB..NEXTB
TICKICB: .EQU ALTBGN + 48 ; Address of the current Input Control Block.
PROFILING: .EQU ALTBGN + 50 ; Non-zero if the profiler is on.
TICKTICKS: .EQU ALTBGN + 52 ; (double) Number of ticks (4ms) since start.
SAVEB: .EQU ALTBGN + 56 ; DE is saved here when used as a temporary.
FORTHWL: .EQU ALTBGN + 58 ; FORTH word list.
ASSEMBLERWL:.EQU ALTBGN + 60 ; ASSEMBLER word list.
; 2 bytes free.
ICBSTART: .EQU ALTBGN + 64 ; Start of the 8, 8-byte Input Control Blocks.
FCBSTART: .EQU ALTBGN + 128; Start of the 8, 8-byte File Control Blocks.
SOESTART: .EQU ALTBGN + 192; Start of the 8, 2-byte Search Order Entries.
; 112 bytes free.
; ======================================================================
; System-provided user variables
;
; User variable offsets are the absolute offset into the Task Page and
; are not an index or count or anything like that. In other words, the
; third User Variable is 4 (0, 2, 4) and not 2 (0, 1, 2).
; ======================================================================
USERSAVEDSP:.EQU 0 ; Saved stack pointer
USERBASE: .EQU 2 ; Number-conversion radix pointer.
USERB: .EQU 4 ; "B" register
USERBEND: .EQU 6 ; "B" register end
NUMUSERVARS:.EQU 4 ; Total number of user variables.
; ======================================================================
; MFORTH Macros
; ======================================================================
; ----------------------------------------------------------------------
; Save and restore DE (corrupts HL).
#DEFINE SAVEDE XCHG\ SHLD SAVED
#DEFINE RESTOREDE LHLD SAVED\ XCHG
; ----------------------------------------------------------------------
; Save and restore BC (corrupts HL).
#DEFINE SAVEBC MOV H,B\ MOV L,C\ SHLD SAVEB
#DEFINE RESTOREBC LHLD SAVEB\ MOV B,H\ MOV C,L
; ======================================================================
; Interrupt Vectors
; ======================================================================
RST0: .ORG 00000h
INX SP
INX SP
JMP INIT
RST1: .ORG 00008h
RET
RST2: .ORG 00010h
RET
RST3: .ORG 00018h
RET
RST4: .ORG 00020h
RET
; Power down interrupt.
TRAP: .ORG 00024h
DI
JMP INTRAP
RST5: .ORG 00028h
RET
RST55: .ORG 0002Ch
DI
JMP INT55
RST6: .ORG 00030h
JMP STDCALL
RST65: .ORG 00034h
DI
JMP INT65
RST7: .ORG 00038h
RET
RST75: .ORG 0003Ch
DI
JMP INT75
; ======================================================================
; The Main ROM tests the two bytes at 40h to see if they contain the
; values "A" and "B". If so, then the Main ROM creates an Option ROM
; trigger file with the name of the remaining six bytes at 42h-47h.
;
; Many Option ROMs use these eight bytes to contain OPON, but we use a
; much more thorough (and thus slightly too-long) variant of OPON that
; protects OPON from interrupts.
;
; In any event, the "AB" mechanism causes problems if you are using REX,
; as the Main ROM will detect that the ROM has changed (between MFORTH
; and REX) and cold boot the computer. We obviously do not want this to
; happen, so we install/overwrite the trigger file ourselves during our
; initialization process.
; ======================================================================
.ORG 00040h
HLT\ HLT\ HLT\ HLT
HLT\ HLT\ HLT\ HLT
; ======================================================================
; Interrupt Handlers
; ======================================================================
; Power down interrupt
INTRAP: CALL INTCALL ; Let the Main ROM turn off the computer
.WORD 00024h ; ..and handle the wake-up sequence.
RET
INT55: CALL INTCALL
.WORD 0002Ch
RET
INT65: CALL INTCALL
.WORD 00034h
RET
INT75: CALL INTCALL
.WORD 0003Ch
PUSH H
PUSH PSW
CALL INCTICKS
POP PSW
POP H
RET
INCTICKS: LXI H,TICKTICKS
INR M
RNZ
INX H
INR M
RNZ
INX H
INR M
RNZ
INR M
RET
; ======================================================================
; Option ROM Support Code
; ======================================================================
; ----------------------------------------------------------------------
; STDON: Switches to the Main ROM.
;
; Here is how the stack looks on entry into this call:
;
; TOS: $0363 (STDCALL: Main ROM code that happens to be "EI; RET")
; T-1: Main ROM routine to call
; T-2: RAM address to return to after the call (OPON in AltLCD)
; T-3: Option ROM address to return to after the call through OPON
;
; This call needs to preserve all registers on entry into the Main ROM.
; Some clever manipulation of the stack is done to ensure that this
; happens. First, we push A+PSW onto the stack since we will use A for
; manipulating the contents of the Cassette Port register at $FF45. This
; means that we need the Main ROM to call POP PSW, RET in order to first
; POP PSW before RETurning to the Main ROM routine. Thankfully the Main ROM
; has those exact two instructions at $26C8.
;
; So we need to get $26C8 onto the stack as the initial return address, but
; to do that we need to use HL. That means that we have to preserve HL
; without pushing it to the stack (since the stack has to be in a specific
; configuration on entry into Main ROM). To do that we first push HL to
; the stack, put $26C8 in HL, and then swap the top-of-stack with HL, thus
; putting $26C8 on the stack and restoring HL.
;
; Here is how the stack looks on entry into the Main ROM:
;
; TOS: $26C8 (Main ROM code that happens to be "POP PSW; RET")
; T-1: PSW
; T-2: $0363 (STDCALL: Main ROM code that happens to be "EI; RET")
; T-3: Main ROM routine to call
; T-4: RAM address to return to after the call (OPON in AltLCD)
; T-5: Option ROM address to return to after the call through OPON
;
; The final RET statement is supplied here for posterity, but in fact by
; the point that the PC gets to that location we will be in the Main ROM.
; Thankfully the Main ROM (both M100 and T200) has a RET statement at $008E,
; so STDON is ORGed in such a way as to ensure that the final RET statement
; falls at $008E.
STDON: .ORG 0007Eh
PUSH PSW ; Preserve A+PSW (which $26C8 POPs).
PUSH H ; Get $26C8 onto the stack
LXI H,026C8h ; ..by swapping the value through HL
XTHL ; ..and the top-of-stack.
LDA 0FF45h ; Get the saved contents of port $E8,
ANI 0FEh ; ..clear the low bit to switch to the Main ROM,
STA 0FF45h ; ..updated the saved contents of the port,
OUT 0E8h ; ..and then actually modify the port.
STDONRET: RET ; Now in Main ROM; return to $26C8.
#IF (STDONRET != $008E)
#ECHO "\t*** ERROR: STDON is not ORGed properly; RET statement not at $008E ***\n"
#ENDIF
; ----------------------------------------------------------------------
; Switches to the Option ROM after a call to the Main ROM.
;
; Here is how the stack looks on entry into this call:
;
; TOS: Option ROM address to return to after the call through OPON
;
; INIT copies this routine into RAM so that the OPON routine is available to
; the Main ROM (which is where it is used). STDON sets up the stack in such
; a way as to ensure that the Main ROM calls this routine after the Main ROM
; call has completed.
;
; This code is interrupt-sensitive, so we disable interrupts until after we
; have properly restore the registers (we only use A+PSW here) and enable
; the Option ROM.
OPONIMG: DI
PUSH PSW
LDA 0FF45h ; Get the saved contents of port $E8,
ORI 001h ; ..set the low bit to switch to the Option ROM,
STA 0FF45h ; ..updated the saved contents of the port,
OUT 0E8h ; ..and then actually modify the port.
POP PSW ; Now in Option ROM; restore A+PSW.
EI
RET ; Return to whatever called STDCALL/INTCALL.
OPONLEN: .EQU $-OPONIMG ; Calculate length of OPON for use by INIT.
; ----------------------------------------------------------------------
; Calls a routine in the Main ROM.
;
; This call needs to preserve all registers on entry into the Main ROM
; and cannot use a register to specify the address of the Main ROM routine
; that is being called. Instead, the Main ROM address is contained in the
; next two bytes of the instruction stream, which are accessed by popping
; the return address from the stack and dereferencing that pointer. The
; real return address is then computed by skipping over the Main ROM address
; that was embedded in the instruction stream and pushing that value onto
; the stack.
;
; This entire process is interrupt-sensitive, so we disable interrupts here
; and then have the Main ROM enable interrupts before it calls the Main ROM
; routine that we are trying to invoke. The Main ROM has the instructions
; "EI; RET" at address $0363, so we push that onto the stack as the initial
; address to return to once in Main ROM. After that we proceed to RET to
; the Main ROM routine that we want to call, then OPON, and then back into
; the Option ROM code that CALLed STDCALL.
;
; Here is the layout of the stack at the point where we JMP STDON:
;
; TOS: $0363 (Main ROM code that happens to be "EI; RET")
; T-1: Main ROM routine to call
; T-2: RAM address to return to after the call (OPON in AltLCD)
; T-3: Option ROM address to return to after the call through OPON
;
; That stack is obviously clear of all of those items on return from STDCALL.
STDCALL: DI
SHLD HOLDH ; Preserve HL
XCHG ; ..and DE
SHLD HOLDD ; ..since we will need them as temporaries.
POP H ; Get the STDCALL return address,
MOV E,M ; ..which is actually the address of the
INX H ; ..Main ROM routine that we want to call,
MOV D,M ; ..and put that address in DE. Then point
INX H ; ..HL at the actual Option ROM return address
PUSH H ; ..and push that address (T-3) to the stack.
LXI H,OPON ; Return from Main ROM through OPON, which we
PUSH H ; ..push onto the stack (T-2).
PUSH D ; Push the Main ROM routine to call (T-1).
LHLD HOLDD ; Restore DE
XCHG ; ..and HL
LHLD HOLDH ; ..so that they can be used as Main ROM args.
PUSH H ; Get $0363 onto the stack
LXI H,00363h ; ..by swapping the value through HL
XTHL ; ..and the top-of-stack.
JMP STDON ; Jump to STDON to get into Main ROM.
; ----------------------------------------------------------------------
; Calls an interrupt handler routine in the Main ROM.
;
; This code is almost identical to STDCALL except that we do not need to
; disable interrupts and we definitely do not want to re-enable them as
; part of the jump into the Main ROM (which STDCALL accomplishes by pushing
; $0363 onto the stack).
;
; Here is the layout of the stack at the point where we JMP STDON:
;
; TOS: Main ROM routine to call
; T-1: RAM address to return to after the call (OPON in AltLCD)
; T-2: Option ROM address to return to after the call through OPON
;
; That stack is obviously clear of all of those items on return from INTCALL.
INTCALL: SHLD INTH ; Preserve HL
XCHG ; ..and DE
SHLD INTD ; ..since we will need them as temporaries.
POP H ; Get the INTCALL return address,
MOV E,M ; ..which is actually the address of the
INX H ; ..Main ROM routine that we want to call,
MOV D,M ; ..and put that address in DE. Then point
INX H ; ..HL at the actual Option ROM return address
PUSH H ; ..and push that address (T-2) to the stack.
LXI H,OPON ; Return from Main ROM through OPON, which we
PUSH H ; ..push onto the stack (T-1).
PUSH D ; Push the Main ROM routine to call (TOS).
LHLD INTD ; Restore DE
XCHG ; ..and HL
LHLD INTH ; ..so that they can be used as Main ROM args.
JMP STDON ; Jump to STDON to get into Main ROM.
; ======================================================================
; MFORTH Initialization
; ======================================================================
; ----------------------------------------------------------------------
; Initialize MFORTH.
;
; This routine is called on a MFORTH cold-start each time that MFORTH is
; activated from the Main ROM Menu. Note that MFORTH does not maintain
; any state between invocations.
;
; We disable interrupts, copy OPON into high memory, call LNKFIL to ensure
; that all of the cached file start addresses are accurate, set up our memory
; map (by figuring out where free space starts and ends), initialize the
; return stack, and JMP to the MFORTH COLD word.
INIT: DI
; Copy OPON into high memory.
LXI D,OPONIMG ; First source byte in DE
LXI H,OPON ; First target byte in HL
MVI B,OPONLEN ; Number of bytes to copy in B
_init1: LDAX D ; Load value from [DE]
MOV M,A ; Save value to [HL]
INX D ; Next source byte
INX H ; Next target byte
DCR B ; Decrement counter
JNZ _init1 ; Keep looping until all bytes are copied
; Call LNKFIL to ensure that the file addresses are accurate.
CALL STDCALL ; Call the
.WORD 02146h ; .."LNKFIL" routine.
; Set up our memory map.
LHLD FRETOP ; Store the beginning of free memory to HL
SHLD TICKTIB ; ..and then to the Terminal Input Buffer.
LXI B,TIBSIZE ; Add TIBSIZE
DAD B ; ..to HL
SHLD DP ; ..and then store that in the Data Pointer.
LXI H,0 ; Get the location of the
DAD SP ; ..OS stack pointer on entry into MFORTH
SHLD BOPSTK ; ..and store it in in BOPSTK.
; Initialize the system word lists.
LXI H,_latestFORTH-NFATOCFASZ
SHLD FORTHWL
LXI H,_latestASSEMBLER-NFATOCFASZ
SHLD ASSEMBLERWL
; Make the FORTH word list the current compilation word
; list; ABORT will initialize the default search order.
LXI H,FORTHWL
SHLD TICKCURRENT
; Four USER variables are currently in use (SavedSP, Base, B, Bend).
LXI H,NUMUSERVARS
SHLD TICKNUMUSERVARS
; Create the first task, which needs to be in place for us
; to enter in to the Inner Interpreter (which needs a return
; stack, for example). The first task begins at the page
; that is below the page where the SP currently resides. This
; could put us right below the system stack (if SP is at xx00,
; for example), but that's okay because we don't actually use
; the system stack for anything (each task has its own stack).
LXI H,1
SHLD TICKNUMTASKS
LXI H,0 ; Get SP
DAD SP ; ..into HL,
LXI B,0100h ; ..then subtract 256
DSUB ; ..from HL to get into the middle of the page,
MVI L,0 ; ..then clear L to get to the start of the page
SHLD TICKFIRSTTASK ;.and then store address of the first task.
MOV B,H ; Put the current task's page into its home in B
MVI C,07fh ; ..and initialize the return stack to xx7F.
MVI M,STACKGUARD; Set the Saved Stack Pointer to the guard
INX H ; ..value since this task will be running (not
MVI M,STACKGUARD; ..resumed by PAUSE) after the JMP to COLD.
MVI L,080h ; Set HL to the parameter stack guard cell
MVI M,STACKGUARD; ..then move the guard value
INX H ; ..into both bytes
MVI M,STACKGUARD; ..of that cell.
MVI L,0ffh ; Initialize the SP, which begins at xxFF.
SPHL
; Disable the profiler.
LXI H,0
SHLD PROFILING
; Reset the tick counter.
LXI H,0
SHLD TICKTICKS
SHLD TICKTICKS+2
; Enable interrupts and jump to COLD (which never returns).
EI
LXI H,COLD ; Point W at COLD (needed by ENTER).
LXI D,COLD ; Point IP at COLD (needed by NEXT).
JMP COLD
; ======================================================================
; MFORTH Kernel and FORTH Word List
; ======================================================================
; Kernel routines and macros.
#include "kernel.asm"
; ANS word sets.
LINK_CORE .EQU NFATOCFASZ
#include "answords/core.asm"
LINK_COREEXT .EQU LAST_CORE
#include "answords/core-ext.asm"
LINK_DOUBLE .EQU LAST_COREEXT
#include "answords/double.asm"
LINK_FACILITY .EQU LAST_DOUBLE
#include "answords/facility.asm"
LINK_FACILITYEXT .EQU LAST_FACILITY
#include "answords/facility-ext.asm"
LINK_FILE .EQU LAST_FACILITYEXT
#include "answords/file.asm"
LINK_SEARCH .EQU LAST_FILE
#include "answords/search.asm"
LINK_SEARCHEXT .EQU LAST_SEARCH
#include "answords/search-ext.asm"
LINK_STRING .EQU LAST_SEARCHEXT
#include "answords/string.asm"
LINK_TOOLS .EQU LAST_STRING
#include "answords/tools.asm"
LINK_TOOLSEXT .EQU LAST_TOOLS
#include "answords/tools-ext.asm"
; MFORTH word sets.
LINK_BREG .EQU LAST_TOOLSEXT
#include "mforthwords/breg.asm"
LINK_MFORTH .EQU LAST_BREG
#include "mforthwords/mforth.asm"
LINK_TASK .EQU LAST_MFORTH
#include "mforthwords/task.asm"
#IFNDEF PROFILER
_latestFORTH .EQU LAST_TASK
#ELSE
LINK_PROFILER .EQU LAST_TASK
#include "mforthwords/profiler.asm"
_latestFORTH .EQU LAST_PROFILER
#ENDIF
; ======================================================================
; Additional Word Lists
; ======================================================================
; ASSEMBLER Word List
LINK_ASSEMBLER .EQU NFATOCFASZ
#include "mforthwords/assembler.asm"
_latestASSEMBLER .EQU LAST_ASSEMBLER
; ======================================================================
; Display ROM statistics.
; ======================================================================
#ECHO "\tEnd of ROM: "
#ECHO $
#ECHO "\n"
; ======================================================================
; Zero-out the rest of the ROM.
; ======================================================================
.ORG 07FFFh
.BYTE 0
; ======================================================================
; Perfect Hash of ROM Dictionary
; ======================================================================
#IFNDEF PHASH
; Temporarily store _latestFORTH at 07FFE for use by phashgen.exe.
.ORG 07FFEh
.WORD _latestFORTH-NFATOCFASZ
#ELSE
; phash.asm already generated.
#include "phash.asm"
#ENDIF
; ======================================================================
; End of ROM.
; ======================================================================
.END
|
copyright zengfr site:http://github.com/zengfr/romhack
00818E move.b ($30,A0), ($79,A1) [123p+ 86]
008194 bra $7e4a [123p+ 79, enemy+79]
008784 move.w ($3a,A0), ($6a,A1) [123p+ 79, enemy+79]
0094DC move.b ($30,A0), D6 [enemy+79]
022CEC move.b D0, ($79,A0)
022CF0 lea ($e0,A0), A0
copyright zengfr site:http://github.com/zengfr/romhack
|
Name: ys_boss1.asm
Type: file
Size: 72901
Last-Modified: '2016-05-13T04:51:16Z'
SHA-1: AAC9DDADCD2E5ED17D88C3C33518E90DC6A064F2
Description: null
|
; CRT0 for the Sharp OZ family
;
; Stefano Bodrato 13 Aug. 2002
;
; Mix of the Dominic's work and the Hi-Tech C modifications
; by the OZDEV team (Alexander R. Pruss, Green, etc..)
;
; all the "$" prefixes have been changed to "s_";
; the "$sp$" label is been changed to "s_sp".
;
; the "-DOZDK" enables the OZ7xx DK compatibility mode
; with extra functions and interrupt handling
; (this causes the DEFINED_ozgetch2 flag to be activated)
;
; - - - - - - -
;
; $Id: oz_crt0.asm,v 1.21 2016-07-09 21:18:54 stefano Exp $
;
; - - - - - - -
MODULE oz_crt0
;-------
; Include zcc_opt.def to find out information about us
;-------
defc crt0 = 1
defc NEED_ansiterminal = 1
INCLUDE "zcc_opt.def"
defc CONSOLE_COLUMNS = 32
defc CONSOLE_ROWS = 10
defc TAR__clib_exit_stack_size = 32
defc TAR__register_sp = -1
; Guess below
defc __CPU_CLOCK = 3072000
INCLUDE "crt/classic/crt_rules.inc"
;-------
; Some general scope declarations
;-------
EXTERN _main ;main() is always external to crt0 code
PUBLIC cleanup ;jp'd to by exit()
PUBLIC l_dcal ;jp(hl)
PUBLIC base_graphics ;Graphical variables
PUBLIC s_filetypetable
PUBLIC saved_hl ;Temporary store used by compiler
PUBLIC saved_de ;for hl and de
; --- OZ related stuff---
PUBLIC ozactivepage ;current mem page
PUBLIC ozmodel ;detected model (call "detect" first)
PUBLIC ozbacklight ;display light status
PUBLIC ozcontrast ;display contrast
PUBLIC ozbacklight_save
PUBLIC s_ozlcdstatus
PUBLIC s_init_unblank ;service entry point to go back from "ozfast" or "ozblankscreen"
PUBLIC ScrCharSet
IF DEFINED_ozgetch2
PUBLIC KeyBufGetPos ;
PUBLIC KeyBufPutPos ; don't
PUBLIC EnableKeyboard
PUBLIC KeyboardBuffer
ENDIF
; --- settings ---
PUBLIC ozkeyrepeatspeed
PUBLIC ozkeyrepeatdelay
PUBLIC ozclick_setting
PUBLIC ozautoofftime
PUBLIC ozautoblanktime
PUBLIC ozautolightofftime
PUBLIC ozprogoptions
; --- -------- ---
defc contrast = 0c026h
defc lcdstatus = 0c024h
org $8000
DEFB 00h, 64h, 09h, 0FEh, 31h, 26h, 48h, 41h
DEFB 30h, 31h, 32h, 0Dh, 75h, 31h, 03h, 0FEh, 5Ah, 0Fh
start:
jr skipname
ozfilename:
defm "BFILNAMEBAS"
defb 00
ozfileowner:
defw 65535
; __ozspare1start:
skipname:
in a,(1)
push af
in a,(2)
push af ; save starting 8000 page
ld a,2
out (1),a
ld a,4
out (2),a ; page first code page into 8000h
jp continue
continue:
ld a,(0c068h) ; backlight state
ld (ozbacklight),a
ld (ozbacklight_save),a
ld hl,(lcdstatus)
ld (s_ozlcdstatus),hl
ld a,(contrast)
ld (ozcontrast),a
di
in a,(7)
;ld (intset),a
ld (intset+1),a
ld a,0ffh-(16+128+1) ;; ARP: was 4+32 !!
out (7),a
call s_swapupperpages
;; now our code is paged in as follows:
;; 8000h: first code page, originally in page 406h
;; a000h: second code page, originally in page 407h
;; c000h: third code page, originally in page 408h
;; e000h: fourth code page, originally in page 409h
;; pages 408h and 409h store the initial contents of c000h-ffffh
;; sp points to 0fe00h
; clear BSS segment (lifted from Hi-Tech C init code, but modified)
;ld de,__Lbss ;Start of BSS segment
;or a ;clear carry
;ld hl,__Hbss
;sbc hl,de ;size of uninitialized data area
;jr z,EmptyBSS
;ld c,l
;ld b,h
;dec bc
;ld l,e
;ld h,d
;inc de
;ld (hl),0
;ldir ;clear memory
;EmptyBSS:
IF DEFINED_ozgetch2
ld hl,KeyBufGetPos
ld (hl),0
ld de,KeyBufGetPos+1
ld bc,26-1
ldir
; ld a,1
; out (19h),a
; ld a,10
; out (17h),a
; xor a
; out (18h),a
; ld a,2
; out (16h),a ;; enable key click
EXTERN ozsetisr
ld hl,ozcustomisr
push hl
call ozsetisr ;; install our ISR
pop bc
ld a,l
or h
jr nz,__exit
ENDIF
;ld hl,1
;push hl
;call _ozclick
;pop hl
;ld hl,argv
;push hl
;ld hl,1
;push hl
;------- Z88DK specific code (begin) -------
ld (__restore_sp_onexit+1),sp ;Save entry stack
INCLUDE "crt/classic/crt_init_sp.asm"
INCLUDE "crt/classic/crt_init_atexit.asm"
call crt0_init_bss
ld (exitsp),sp
; Optional definition for auto MALLOC init
; it assumes we have free space between the end of
; the compiled program and the stack pointer
IF DEFINED_USING_amalloc
INCLUDE "crt/classic/crt_init_amalloc.asm"
ENDIF
;-------- Z88DK specific code (end) -------
call _main ;call main program
; __ozspare1end:
;------- Z88DK specific code (begin) -------
cleanup:
call crt0_exit
__restore_sp_onexit:
ld sp,0 ;Restore stack to entry value
;ret
;-------- Z88DK specific code (end) -------
;pop hl
;pop hl ; argv (??)
_ozexitrestoreint:
_exit:
ld a,7
out (3),a
ld a,4
out (4),a ;; page in proper second page
;call __ozcallexitfunctions
__exit:
s_init_unblank: ; ozblankscreen or ozfast might have hidden everything;
call ret_only ; if so, ret_only is changed into "ozunblankscreen" to make it back visible.
di
;intset equ $+1
intset: ld a,0ffh
out (7),a
im 1
call s_swapupperpages
call s_clearbacklighttimer
;; restore a bunch of stuff
ld a,(ozbacklight_save)
ld (0c068h),a
ld hl,(s_ozlcdstatus)
ld (lcdstatus),hl ;; restore right LCD Status
ld a,(ozcontrast)
ld (contrast),a
IF DEFINED_ozgetch2
ld hl,KeyBufGetPos ;; put keyboard buffer in standard buffer
ld de,0c031h
ld bc,24
ldir
ENDIF
s_wipe_hook:
nop
nop
nop
; ld hl,0406h
; ld c,4
; out (c),h
; dec c
; out (c),l
; dec c
ld a,6
out (3),a
ld a,4
out (4),a
jp continue2+2000h
continue2:
; pop hl
; out (c),h
; dec c
; out (c),l ; restore starting page
pop af
out (2),a
pop af
out (1),a
xor a
out (22h),a ; restore default display page
ei
_bdos: ;; dummy routines
ret
s_sp:
defw 0fe00h
swapret: defw 0
s_swapupperpages: ;; must be called with interrupts disabled
pop bc
ld (s_swapupperpages_ret+1),bc
ld a,8
out (3),a
ld a,4 ; page in page 408 at 0a000h
out (4),a
ld d,0c0h
call s_swappage ; swap 0a000h page with 0c000h page
ld a,9
out (3),a
; ld a,4
; out (4),a ; page in page 409 at 0a000h
ld d,0e0h
call s_swappage ; swap 0a000h page with 0e000h page
ld hl,0
add hl,sp
ld de,(s_sp)
ld (s_sp),hl
ex de,hl
ld sp,hl
s_swapupperpages_ret: jp 0
;s_swapupperpages_ret equ $-2
s_swappage: ;; must be called with interrupts disabled!
;; swaps pages at a000 and at d*256
pop bc
ld (s_swappage_ret+1),bc
ld hl,0
add hl,sp
ld (s_saved_sp+1),hl
ld hl,0a000h
ld sp,hl
ld e,l
ex de,hl
ld a,h
add a,20h ; end marker
top:
pop bc ;10
ld e,(hl) ;7
ld (hl),c ;7
inc l ;4
ld d,(hl) ;7
ld (hl),b ;7
inc l ;4
push de ;11
pop de ;10 ;SP=SP+2
pop bc ;10
ld e,(hl)
ld (hl),c
inc l
ld d,(hl)
ld (hl),b
inc l
push de
pop de
jp nz,top ;10
inc h
cp h
jp nz,top
s_saved_sp: ld hl,0000 ;;
;s_saved_sp equ $-2 ;; self-mod
ld sp,hl
ld a,7
out (3),a
;; ld a,4
;; out (4),a ; page in second code page
s_swappage_ret: jp 0
;$swappage_ret equ $-2
s_32kintoff:
di
im 1
ret_only:
ret
s_32kinton:
ld a,0feh
ld i,a
im 2
ei
ret
s_clearbacklighttimer:
ld hl,0
ld (0c00dh),hl
ld hl,(s_ozlcdstatus)
ld (lcdstatus),hl
ret
ozbacklight:
defb 0
ozbacklight_save:
defb 0
ozcontrast:
defb 0
s_ozlcdstatus:
defw 0
; Keyboard and interrupts
INCLUDE "target/oz/classic/oz_customisr.def"
IF DEFINED_ozgetch2
KeyBufGetPos: defb 0
KeyBufPutPos: defb 0
KeyboardBuffer: ; 123456789012345678901234
defm "(c)Pruss,Green,&c vZ88DK"
ENDIF
ScrCharSet: defb 1
;argv: defw __ozfilename
EnableKeyboard: defs 1
;HeapTop EQU 0f980h
;Model32k EQU 1
;------------------------------------------
;------------------------------------------
; End of startup part, routines following
;------------------------------------------
;------------------------------------------
l_dcal:
jp (hl)
defc ansipixels = 236
IF !DEFINED_ansicolumns
defc DEFINED_ansicolumns = 1
defc ansicolumns = 59
ENDIF
INCLUDE "crt/classic/crt_runtime_selection.asm"
INCLUDE "crt/classic/crt_section.asm"
SECTION bss_crt
saved_hl: defw 0 ; Temp store for hl
saved_de: defw 0 ; Temp store for de
ozactivepage: defw 0 ; Page number for the graph map (0400h for 0A000h)
ozmodel: defb 0 ; Set with "ozdetectmodel" (see libraries)
s_filetypetable: defw 0
SECTION code_crt_init
ld hl,0xa000
ld (base_graphics),hl
ld hl,0x0400
ld (ozactivepage),hl
ld hl,0xc089
ld (s_filetypetable),hl
ld a,1
ld (ozmodel),a
; --- settings - leave untouched ---
SECTION data_crt
ozkeyrepeatspeed:
defb 5
ozkeyrepeatdelay:
defb 32
ozclick_setting:
defb 1
ozautoofftime:
defw 60*180 ;; 3 hours
ozautoblanktime:
defw 240 ;; 4 minutes
ozautolightofftime:
defw 120 ;; 2 minutes
ozprogoptions:
defb 0
;; padding (for future expansion)
defb 0,0,0,0
|
; A061420: a(n) = a(ceiling((n-1)*2/3)) + 1 with a(0) = 0.
; 0,1,2,3,3,4,4,4,5,5,5,5,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13
lpb $0
mul $0,4
div $0,6
add $1,1
lpe
|
/* Copyright 2015 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/core/util/device_name_utils.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
namespace tensorflow {
namespace {
bool RoundTripParsedName(const string& original, const string& expected) {
DeviceNameUtils::ParsedName p;
if (!DeviceNameUtils::ParseFullName(original, &p)) {
return false;
}
string round_tripped = DeviceNameUtils::ParsedNameToString(p);
return (round_tripped == expected);
}
enum NamePart { kJob = 0x01, kReplica = 0x02, kTask = 0x04, kDevice = 0x08 };
bool RoundTripPartialName(int parts_to_test, const std::vector<string>& parts,
bool explicitDevice) {
string original, expected;
if (parts_to_test & kJob) {
strings::StrAppend(&original, "/job:", parts[0]);
strings::StrAppend(&expected, "/job:", parts[0]);
}
if (parts_to_test & kReplica) {
strings::StrAppend(&original, "/replica:", parts[1]);
strings::StrAppend(&expected, "/replica:", parts[1]);
}
if (parts_to_test & kTask) {
strings::StrAppend(&original, "/task:", parts[2]);
strings::StrAppend(&expected, "/task:", parts[2]);
}
if (parts_to_test & kDevice) {
if (explicitDevice) {
strings::StrAppend(&original, "/device:", parts[3]);
strings::StrAppend(&expected, "/device:", parts[3]);
} else {
strings::StrAppend(&original, "/", parts[3]);
strings::StrAppend(&expected, "/device:", str_util::Uppercase(parts[3]));
}
}
return RoundTripParsedName(original, expected);
}
} // namespace
TEST(DeviceNameUtilsTest, Basic) {
EXPECT_EQ(DeviceNameUtils::FullName("hello", 1, 2, "CPU", 3),
"/job:hello/replica:1/task:2/device:CPU:3");
{
DeviceNameUtils::ParsedName p;
EXPECT_FALSE(DeviceNameUtils::ParseFullName("foobar", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:123/replica:1/task:2/device:GPU:3", &p));
EXPECT_FALSE(
DeviceNameUtils::ParseFullName("/job:123/replica:1/task:2/gpu:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:123/replica:1/task:2/device:gpu:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:-1/task:2/device:GPU:3", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:-2/device:GPU:3", &p));
EXPECT_FALSE(
DeviceNameUtils::ParseFullName("/job:foo/replica:1/task:2/bar:3", &p));
EXPECT_FALSE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:2/device:GPU:3/extra", &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
// Allow _ in job names.
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo_bar/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo_bar");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
// Allow _ in job names.
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:foo_bar/replica:1/task:2/device:GPU:3", &p));
EXPECT_TRUE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_TRUE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.job, "foo_bar");
EXPECT_EQ(p.replica, 1);
EXPECT_EQ(p.task, 2);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 3);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/job:*/replica:4/gpu:*", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/replica:4/device:GPU:*", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/device:GPU/replica:4", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(
"/job:*/replica:4/device:myspecialdevice:13", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "myspecialdevice");
EXPECT_EQ(p.id, 13);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/", &p));
EXPECT_FALSE(p.has_job);
EXPECT_FALSE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_FALSE(p.has_type);
EXPECT_FALSE(p.has_id);
}
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(
DeviceNameUtils::ParseFullName("/job:*/replica:4/device:GPU:5", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_TRUE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
EXPECT_EQ(p.id, 5);
}
{ // Same result if we reorder the components
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseFullName("/gpu:*/job:*/replica:4", &p));
EXPECT_FALSE(p.has_job);
EXPECT_TRUE(p.has_replica);
EXPECT_FALSE(p.has_task);
EXPECT_TRUE(p.has_type);
EXPECT_FALSE(p.has_id);
EXPECT_EQ(p.replica, 4);
EXPECT_EQ(p.type, "GPU");
}
EXPECT_TRUE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:1/task:2/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:1/task:3/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:foo/replica:10/task:2/device:GPU:4"));
EXPECT_FALSE(DeviceNameUtils::IsSameAddressSpace(
"/job:foo/replica:1/task:2/cpu:3",
"/job:bar/replica:1/task:2/device:GPU:4"));
EXPECT_EQ(DeviceNameUtils::LocalName("CPU", 1), "/device:CPU:1");
EXPECT_EQ(DeviceNameUtils::LocalName("GPU", 2), "/device:GPU:2");
EXPECT_EQ(DeviceNameUtils::LocalName("MySpecialDevice", 13),
"/device:MySpecialDevice:13");
EXPECT_EQ(
DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/device:CPU:3"),
"/device:CPU:3");
EXPECT_EQ(DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/cpu:3"),
"/device:CPU:3");
EXPECT_EQ(
DeviceNameUtils::LocalName("/job:foo/replica:1/task:2/device:abc:73"),
"/device:abc:73");
{
DeviceNameUtils::ParsedName p;
EXPECT_TRUE(DeviceNameUtils::ParseLocalName("CPU:10", &p));
EXPECT_EQ(p.type, "CPU");
EXPECT_EQ(p.id, 10);
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("cpu:abc", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("abc:", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("abc", &p));
EXPECT_FALSE(DeviceNameUtils::ParseLocalName("myspecialdevice", &p));
}
// Test that all parts are round-tripped correctly.
{
for (int i = 0; i < 0x10; ++i) {
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "CPU:3"},
/*explicitDevice=*/false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "GPU:3"},
/*explicitDevice=*/false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "cpu:3"},
/*explicitDevice=*/false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "gpu:3"},
/*explicitDevice=*/false));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "CPU:3"},
/*explicitDevice=*/true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "GPU:3"},
/*explicitDevice=*/true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "cpu:3"},
/*explicitDevice=*/true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "gpu:3"},
/*explicitDevice=*/true));
EXPECT_TRUE(RoundTripPartialName(i, {"foo", "3", "2", "someDevice:3"},
/*explicitDevice=*/true));
}
}
}
static bool IsCSHelper(StringPiece pattern, StringPiece actual) {
DeviceNameUtils::ParsedName p, a;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(pattern, &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(actual, &a));
return DeviceNameUtils::IsCompleteSpecification(p, a);
}
TEST(DeviceNameUtilsTest, IsCompleteSpecification) {
EXPECT_TRUE(IsCSHelper("/job:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(
IsCSHelper("/job:*/task:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*/task:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsCSHelper("/job:*/replica:*/gpu:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsCSHelper("/cpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsCSHelper("/device:GPU:2", "/job:worker/replica:1/task:2/device:GPU:1"));
EXPECT_TRUE(
IsCSHelper("/gpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
}
static bool IsSpecHelper(StringPiece pattern, StringPiece actual) {
DeviceNameUtils::ParsedName p, a;
EXPECT_TRUE(DeviceNameUtils::ParseFullName(pattern, &p));
EXPECT_TRUE(DeviceNameUtils::ParseFullName(actual, &a));
return DeviceNameUtils::IsSpecification(p, a);
}
TEST(DeviceNameUtilsTest, IsSpecification) {
EXPECT_TRUE(
IsSpecHelper("/job:*", "/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work/replica:1/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work/replica:1"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/replica:1"));
EXPECT_TRUE(IsSpecHelper("/job:*", "/job:work"));
EXPECT_TRUE(IsSpecHelper("/job:*/replica:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/gpu:*",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/device:GPU:3",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:1/task:2",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/job:work/replica:*/task:2",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/task:*", "/job:*/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/task:2", "/job:*/replica:1/task:2/device:GPU:3"));
EXPECT_TRUE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2/cpu:1"));
EXPECT_TRUE(IsSpecHelper("/cpu:0", "/cpu:0"));
EXPECT_TRUE(
IsSpecHelper("/gpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(
IsSpecHelper("/job:worker/replica:1/task:2/device:GPU:3", "/gpu:*"));
EXPECT_FALSE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2"));
EXPECT_FALSE(IsSpecHelper("/cpu:*", "/job:*/replica:1/task:2/device:GPU:1"));
EXPECT_FALSE(
IsSpecHelper("/cpu:*", "/job:worker/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(IsSpecHelper("/device:GPU:2",
"/job:worker/replica:1/task:2/device:GPU:1"));
EXPECT_FALSE(IsSpecHelper("/job:work/replica:*/task:0",
"/job:work/replica:1/task:2/device:GPU:3"));
EXPECT_FALSE(IsSpecHelper("/job:work/replica:0/task:2",
"/job:work/replica:*/task:2/device:GPU:3"));
}
TEST(DeviceNameUtilsTest, SplitDeviceName) {
string task;
string device;
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName(
"/job:foo/replica:1/task:2/cpu:1", &task, &device));
EXPECT_EQ("/job:foo/replica:1/task:2", task);
EXPECT_EQ("CPU:1", device);
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName(
"/job:foo/cpu:1/task:2/replica:1", &task, &device));
EXPECT_EQ("/job:foo/replica:1/task:2", task);
EXPECT_EQ("CPU:1", device);
EXPECT_TRUE(
DeviceNameUtils::SplitDeviceName("/device:GPU:3", &task, &device));
EXPECT_EQ("", task);
EXPECT_EQ("GPU:3", device);
EXPECT_FALSE(DeviceNameUtils::SplitDeviceName("gpu:3", &task, &device));
EXPECT_FALSE(DeviceNameUtils::SplitDeviceName("/job:foo/task:2/replica:1",
&task, &device));
EXPECT_TRUE(DeviceNameUtils::SplitDeviceName("/device:myspecialdevice:3",
&task, &device));
EXPECT_EQ("", task);
EXPECT_EQ("myspecialdevice:3", device);
}
static DeviceNameUtils::ParsedName Name(const string& str) {
DeviceNameUtils::ParsedName ret;
CHECK(DeviceNameUtils::ParseFullName(str, &ret)) << "Invalid name: " << str;
return ret;
}
static void MergeDevNamesHelperImpl(const string& name_a, const string& name_b,
const string& expected_merge_name,
bool allow_soft_placement) {
DeviceNameUtils::ParsedName target_a = Name(name_a);
TF_EXPECT_OK(DeviceNameUtils::MergeDevNames(&target_a, Name(name_b),
allow_soft_placement));
DeviceNameUtils::ParsedName target_b = Name(name_b);
TF_EXPECT_OK(DeviceNameUtils::MergeDevNames(&target_b, Name(name_a),
allow_soft_placement));
EXPECT_EQ(target_a, target_b);
EXPECT_EQ(target_a, Name(expected_merge_name));
EXPECT_EQ(target_b, Name(expected_merge_name));
}
static void MergeDevNamesHelper(const string& name_a, const string& name_b,
const string& expected_merge_name) {
MergeDevNamesHelperImpl(name_a, name_b, expected_merge_name, false);
}
static void MergeDevNamesHelperAllowSoftPlacement(
const string& name_a, const string& name_b,
const string& expected_merge_name) {
MergeDevNamesHelperImpl(name_a, name_b, expected_merge_name, true);
}
static void MergeDevNamesError(const string& name_a, const string& name_b,
const string& expected_error_substr) {
DeviceNameUtils::ParsedName target_a = Name(name_a);
Status s = DeviceNameUtils::MergeDevNames(&target_a, Name(name_b));
EXPECT_EQ(s.code(), error::INVALID_ARGUMENT);
EXPECT_TRUE(str_util::StrContains(s.error_message(), expected_error_substr))
<< s;
}
TEST(DeviceNameUtilsTest, MergeDevNames) {
DeviceNameUtils::ParsedName target;
// Idempotence tests.
MergeDevNamesHelper("", "", "");
MergeDevNamesHelper("/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1",
"/job:foo/replica:1/task:2/cpu:1");
// Merging with empty device has no effect.
MergeDevNamesHelper("", "/job:foo", "/job:foo");
MergeDevNamesHelper("", "/replica:2", "/replica:2");
MergeDevNamesHelper("", "/task:7", "/task:7");
// MergeDevNamesHelper("", "/device:GPU:1", "/device:GPU:1");
// Combining disjoint names.
MergeDevNamesHelper("/job:foo", "/task:7", "/job:foo/task:7");
MergeDevNamesHelper("/job:foo", "/device:GPU:1", "/job:foo/device:GPU:1");
// Combining overlapping names.
MergeDevNamesHelper("/job:foo/replica:0", "/replica:0/task:1",
"/job:foo/replica:0/task:1");
// Wildcard tests.
MergeDevNamesHelper("", "/gpu:*", "/gpu:*");
MergeDevNamesHelper("/gpu:*", "/gpu:*", "/gpu:*");
MergeDevNamesHelper("/device:GPU:1", "/gpu:*", "/device:GPU:1");
// Incompatible components.
MergeDevNamesError("/job:foo", "/job:bar", "incompatible jobs");
MergeDevNamesError("/replica:0", "/replica:1", "incompatible replicas");
MergeDevNamesError("/task:0", "/task:1", "incompatible tasks");
MergeDevNamesError("/gpu:*", "/cpu:*", "incompatible types");
MergeDevNamesError("/device:GPU:0", "/device:GPU:1", "incompatible ids");
}
TEST(DeviceNameUtilsTest, MergeDevNamesAllowSoftPlacement) {
// Incompatible components with allow_soft_placement.
MergeDevNamesHelperAllowSoftPlacement("/gpu:*", "/cpu:1", "");
MergeDevNamesHelperAllowSoftPlacement("/cpu:*", "/device:GPU:1", "");
MergeDevNamesHelperAllowSoftPlacement("/device:GPU:1", "/device:GPU:2",
"/device:GPU:*");
}
TEST(DeviceNameUtilsTest, GetNamesForDeviceMappings) {
DeviceNameUtils::ParsedName p =
Name("/job:foo/replica:10/task:0/device:GPU:1");
EXPECT_EQ(str_util::Join(DeviceNameUtils::GetNamesForDeviceMappings(p), ","),
"/job:foo/replica:10/task:0/device:GPU:1,"
"/job:foo/replica:10/task:0/gpu:1");
p.has_task = false;
EXPECT_EQ(str_util::Join(DeviceNameUtils::GetNamesForDeviceMappings(p), ","),
"");
}
TEST(DeviceNameUtilsTest, CanonicalizeDeviceName) {
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1",
DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/replica:10/task:0/device:CPU:1"));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1",
DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica:10/device:CPU:1"));
EXPECT_EQ("/job:foo/replica:10/task:0/device:CPU:1",
DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica:10/cpu:1"));
EXPECT_EQ("/device:CPU:0", DeviceNameUtils::CanonicalizeDeviceName("CPU:0"));
EXPECT_EQ("", DeviceNameUtils::CanonicalizeDeviceName(
"/job:foo/task:0/replica/cpu:1"));
}
static void BM_ParseFullName(int iters) {
DeviceNameUtils::ParsedName p;
while (iters--) {
DeviceNameUtils::ParseFullName("/job:worker/replica:3/task:0/cpu:0", &p);
}
}
BENCHMARK(BM_ParseFullName);
} // namespace tensorflow
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ============================================================
//
// AssemblyBinder.hpp
//
//
// Defines the AssemblyBinder class
//
// ============================================================
#ifndef __BINDER__ASSEMBLY_BINDER_HPP__
#define __BINDER__ASSEMBLY_BINDER_HPP__
#include "bindertypes.hpp"
#include "bindresult.hpp"
#include "bundle.h"
class CLRPrivBinderCoreCLR;
class PEAssembly;
class PEImage;
class AssemblyLoadContext;
namespace BINDER_SPACE
{
class AssemblyBinder
{
public:
// See code:BINDER_SPACE::AssemblyBinder::GetAssembly for info on fNgenExplicitBind
// and fExplicitBindToNativeImage, and see code:CEECompileInfo::LoadAssemblyByPath
// for an example of how they're used.
static HRESULT BindAssembly(/* in */ ApplicationContext *pApplicationContext,
/* in */ AssemblyName *pAssemblyName,
/* in */ LPCWSTR szCodeBase,
/* in */ PEAssembly *pParentAssembly,
/* in */ BOOL fNgenExplicitBind,
/* in */ BOOL fExplicitBindToNativeImage,
/* in */ bool excludeAppPaths,
/* out */ Assembly **ppAssembly);
static HRESULT BindToSystem(/* in */ SString &systemDirectory,
/* out */ Assembly **ppSystemAssembly,
/* in */ bool fBindToNativeImage);
static HRESULT BindToSystemSatellite(/* in */ SString &systemDirectory,
/* in */ SString &simpleName,
/* in */ SString &cultureName,
/* out */ Assembly **ppSystemAssembly);
static HRESULT GetAssembly(/* in */ SString &assemblyPath,
/* in */ BOOL fIsInGAC,
/* in */ BOOL fExplicitBindToNativeImage,
/* out */ Assembly **ppAssembly,
/* in */ LPCTSTR szMDAssemblyPath = NULL,
/* in */ BundleFileLocation bundleFileLocation = BundleFileLocation::Invalid());
#if !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
static HRESULT BindUsingHostAssemblyResolver (/* in */ INT_PTR pManagedAssemblyLoadContextToBindWithin,
/* in */ AssemblyName *pAssemblyName,
/* in */ CLRPrivBinderCoreCLR *pTPABinder,
/* in */ AssemblyLoadContext *pBinder,
/* out */ Assembly **ppAssembly);
static HRESULT BindUsingPEImage(/* in */ ApplicationContext *pApplicationContext,
/* in */ BINDER_SPACE::AssemblyName *pAssemblyName,
/* in */ PEImage *pPEImage,
/* in */ PEKIND peKind,
/* in */ IMDInternalImport *pIMetaDataAssemblyImport,
/* [retval] [out] */ Assembly **ppAssembly);
#endif // !defined(DACCESS_COMPILE) && !defined(CROSSGEN_COMPILE)
static HRESULT TranslatePEToArchitectureType(DWORD *pdwPAFlags, PEKIND *PeKind);
private:
static HRESULT BindByName(/* in */ ApplicationContext *pApplicationContext,
/* in */ AssemblyName *pAssemblyName,
/* in */ bool skipFailureCaching,
/* in */ bool skipVersionCompatibilityCheck,
/* in */ bool excludeAppPaths,
/* out */ BindResult *pBindResult);
// See code:BINDER_SPACE::AssemblyBinder::GetAssembly for info on fNgenExplicitBind
// and fExplicitBindToNativeImage, and see code:CEECompileInfo::LoadAssemblyByPath
// for an example of how they're used.
static HRESULT BindWhereRef(/* in */ ApplicationContext *pApplicationContext,
/* in */ PathString &assemblyPath,
/* in */ BOOL fNgenExplicitBind,
/* in */ BOOL fExplicitBindToNativeImage,
/* in */ bool excludeAppPaths,
/* out */ BindResult *pBindResult);
static HRESULT BindLocked(/* in */ ApplicationContext *pApplicationContext,
/* in */ AssemblyName *pAssemblyName,
/* in */ bool skipVersionCompatibilityCheck,
/* in */ bool excludeAppPaths,
/* out */ BindResult *pBindResult);
static HRESULT FindInExecutionContext(/* in */ ApplicationContext *pApplicationContext,
/* in */ AssemblyName *pAssemblyName,
/* out */ ContextEntry **ppContextEntry);
static HRESULT BindByTpaList(/* in */ ApplicationContext *pApplicationContext,
/* in */ AssemblyName *pRequestedAssemblyName,
/* in */ bool excludeAppPaths,
/* out */ BindResult *pBindResult);
static HRESULT Register(/* in */ ApplicationContext *pApplicationContext,
/* in */ BindResult *pBindResult);
static HRESULT RegisterAndGetHostChosen(/* in */ ApplicationContext *pApplicationContext,
/* in */ LONG kContextVersion,
/* in */ BindResult *pBindResult,
/* out */ BindResult *pHostBindResult);
static HRESULT OtherBindInterfered(/* in */ ApplicationContext *pApplicationContext,
/* in */ BindResult *pBindResult);
};
};
#endif
|
; A112704: Partial sum of Catalan numbers A000108 multiplied by powers of 10.
; Submitted by Christian Krause
; 1,11,211,5211,145211,4345211,136345211,4426345211,147426345211,5009426345211,172969426345211,6051569426345211,214063569426345211,7643063569426345211,275087063569426345211,9969932063569426345211
lpb $0
mul $1,2
mov $2,$0
sub $0,1
mul $1,5
seq $2,108 ; Catalan numbers: C(n) = binomial(2n,n)/(n+1) = (2n)!/(n!(n+1)!).
add $1,$2
lpe
mov $0,$1
mul $0,10
add $0,1
|
#include <iostream>
#include <sstream>
#include "priorityQueueLL.h"
using namespace std;
PriorityQueue::PriorityQueue(){
}
PriorityQueue::PriorityQueue(string inName, int inTimeToDelivery, int inTreatmentTime){
Patient *newp = new Patient(inName, inTimeToDelivery, inTreatmentTime);
head = newp;
}
PriorityQueue::~PriorityQueue(){
}
void PriorityQueue::enqueuePatient(string newPatient){
Patient *p = new Patient();
stringstream ss(newPatient);
string line;
string name;
int timeToDelivery;
int treatmentTime;
int count = 1;
while(getline(ss, line, ',')){
if(count == 1){
p->name = line;
name = line;
}
else if(count == 2){
p->timeToDelivery = stoi(line);
timeToDelivery = stoi(line);
}
else if(count == 3){
p->treatmentTime = stoi(line);
treatmentTime = stoi(line);
}
count++;
}
p->next = NULL;
p->previous = NULL;
if(head == NULL){
head = new Patient(name, timeToDelivery, treatmentTime);
}
else{
Patient *tmp = new Patient();
tmp = head;
bool run = true;
while(run){
if(tmp->timeToDelivery < p->timeToDelivery){
if(tmp->next != NULL){
tmp = tmp->next;
}
else{
tmp->next = p;
p->previous = tmp;
run = false;
}
}
else if(tmp->timeToDelivery == p->timeToDelivery){
if(tmp->treatmentTime < p->treatmentTime && tmp->next->timeToDelivery != p->timeToDelivery){
p->next = tmp->next;
p->previous = tmp;
tmp->next->previous = p;
tmp->next = p;
run = false; //exit loop, patient added
}
else if(tmp->treatmentTime > p->treatmentTime){
p->next = tmp;
p->previous = tmp->previous;
if(tmp!=head){
tmp->previous->next = p;
}
else{
head = p;
}
tmp->previous = p;
run = false; //exit loop, patient added
}
else if(tmp->treatmentTime == p->treatmentTime){
p->next = tmp;
p->previous = tmp->previous;
tmp->previous->next = p;
tmp->previous = p;
run = false;
}
else if(tmp->treatmentTime < p->treatmentTime && tmp->next->timeToDelivery == p->timeToDelivery){
tmp = tmp->next;
}
}
else{
if(tmp == head && p->timeToDelivery < tmp->timeToDelivery){
tmp->previous = p;
p->next = tmp;
head = p;
run = false; //exit loop, patient added
}
else{
tmp->previous->next = p;
p->previous = tmp->previous;
p->next = tmp;
tmp->previous = p;
run = false;
}
}
}
}
}
void PriorityQueue::dequeuePatient(){
//dequeues a single patient, with the top priority
Patient *tmp = new Patient();
tmp = head;
head = tmp->next;
cout<<"Dequeued: "<<tmp->name<<", Priority: "<<tmp->timeToDelivery<<", Treatment: "<<tmp->treatmentTime<<endl;
tmp->next = NULL;
head->previous = NULL;
delete tmp;
}
void PriorityQueue::dequeueList(int size){
int counter = 1;
Patient *tmp = new Patient;
tmp = head;
while(counter < size){
tmp = head;
cout<<counter<<": "<<tmp->name<<", "<<tmp->timeToDelivery<<", "<<tmp->treatmentTime<<endl;
head = head->next;
head->previous = NULL;
tmp->next = NULL;
delete tmp;
counter++;
}
cout<<counter<<": "<<head->name<<", "<<head->timeToDelivery<<", "<<head->treatmentTime<<endl;
delete head;
head = NULL;
}
|
; A146880: A symmetrical triangle sequence of coefficients : p(x,n)=If[n == 0, 1, (x + 1)^n + Sum[(1 + Mod[Binomial[n, m], 2])*x^m*(1 + x^(n - 2*m)), {m, 1, n - 1}]].
; 1,1,1,1,4,1,1,7,7,1,1,6,8,6,1,1,9,12,12,9,1,1,8,19,22,19,8,1,1,11,25,39,39,25,11,1,1,10,30,58,72,58,30,10,1,1,13,38,86,128,128,86,38,13,1,1,12,49,122,212,254,212,122,49,12,1
seq $0,173741 ; T(n,k) = binomial(n,k) + 4 for 1 <= k <= n - 1, n >= 2, and T(n,0) = T(n,n) = 1 for n >= 0, triangle read by rows.
seq $0,124356 ; Number of (directed) Hamiltonian cycles on the Moebius ladder graph M_n (for n>=4).
div $0,2
sub $0,3
|
;; Tells the assembler that we're bootsector & sets our offset in memory.
[org 0x7c00]
mov [BOOT_DRIVE], dl ; BIOS stores our boot drive in dl.
mov bp, 0x9000 ; Sets the stack.
mov sp, bp
mov bx, STR_REAL_MODE
call puts16
call load_kernel
call switch_to_pm ; We never return from here.
;; Include subroutines.
%include "boot/utils/puts16.asm"
%include "boot/utils/putspm.asm"
%include "boot/utils/print_hex.asm"
%include "boot/utils/load_disk.asm"
%include "boot/gdt.asm"
%include "boot/switch_pm.asm"
[bits 16]
load_kernel:
mov bx, STR_LD_KERNEL
call puts16
;; Sets parameters for load_disk, so that we load the first 15 sectors,
;; excluding boot sector, from the boot disk (i.e. our kernel code )
;; to the adresse KERNEL_OFFSET
mov bx, KERNEL_OFFSET
mov dh, 2 ; Magic value, we could load more to be certain.
mov dl, [BOOT_DRIVE]
call load_disk
ret
[bits 32]
;; This is where we land after pm switch & init.
begin_pm:
mov ebx, STR_PROT_MODE
call puts_pm
call KERNEL_OFFSET ; Jump to where we loaded our Kernel.
jmp $ ; Hang
;; DATA
KERNEL_OFFSET: equ 0x1000 ; Memory offset to which we'll load our kernel.
BOOT_DRIVE: db 0 ; Disk number.
STR_REAL_MODE: db "Started in 16-bit Real Mode.",0
STR_LD_KERNEL: db "Loading Kernel.",0
STR_PROT_MODE: db "Successfully landed in 32-bit Protected Mode.",0
;; Padding & Magic BIOS Number.
times 510-($-$$) db 0
dw 0xaa55
|
/*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "StdAfx.h"
#include <QtWidgets/QDialog>
#include <QtWidgets/QDialogButtonBox>
#include <QtWidgets/QTreeWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QPushButton>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QSplitter>
#include "SliceRelationshipWidget.hxx"
#include <AzFramework/Entity/EntityContextBus.h>
#include <AzToolsFramework/API/ToolsApplicationAPI.h>
#include <AzToolsFramework/AssetBrowser/AssetSelectionModel.h>
namespace SliceRelationshipWidgetInternal
{
//! The icon to use when a cycle is detected.
static const char* s_cycleDetectedIcon = ":/Cards/img/UI20/Cards/warning.png";
//! the formatting string used a cycle is detected. %1 is the name of the child item.
static const char* s_cycleDetectedFormatter = " CYCLE DETECTED: %1";
}
namespace AzToolsFramework
{
void SliceRelationshipWidget::closeEvent(QCloseEvent* event)
{
QWidget::closeEvent(event);
}
//=========================================================================
// SlicePushWidget
//=========================================================================
SliceRelationshipWidget::SliceRelationshipWidget(QWidget* parent)
: QWidget(parent)
{
QVBoxLayout* layout = new QVBoxLayout();
// Window layout:
// ===============================================
// ||-------------------------------------------||
// || | ||
// || | ||
// || | ||
// || (splitter) ||
// || | ||
// || (Dependents tree) | (Dependencies tree) ||
// || | ||
// || | ||
// || | ||
// ||-------------------------------------------||
// || (button box) ||
// ===============================================
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_sliceDependencyTree = new QTreeWidget();
m_sliceDependencyTree->setColumnCount(1);
m_sliceDependencyTree->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_sliceDependencyTree->setDragDropMode(QAbstractItemView::DragDropMode::NoDragDrop);
m_sliceDependencyTree->setDragEnabled(false);
m_sliceDependencyTree->header()->setStretchLastSection(false);
m_sliceDependencyTree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
m_sliceDependencyTree->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
m_sliceDependencyTree->setFocusPolicy(Qt::FocusPolicy::NoFocus);
m_sliceDependencyTree->setColumnCount(1);
m_sliceDependencyTree->setHeaderLabel(tr("Dependencies"));
m_sliceDependentsTree = new QTreeWidget();
m_sliceDependentsTree->setColumnCount(1);
m_sliceDependentsTree->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_sliceDependentsTree->setDragDropMode(QAbstractItemView::DragDropMode::NoDragDrop);
m_sliceDependentsTree->setDragEnabled(false);
m_sliceDependentsTree->header()->setStretchLastSection(false);
m_sliceDependentsTree->header()->setSectionResizeMode(0, QHeaderView::ResizeToContents);
m_sliceDependentsTree->setSelectionMode(QAbstractItemView::SelectionMode::NoSelection);
m_sliceDependentsTree->setFocusPolicy(Qt::FocusPolicy::NoFocus);
m_sliceDependentsTree->setColumnCount(1);
m_sliceDependentsTree->setHeaderLabel(tr("Dependents"));
// Main splitter contains left & right widgets (the two trees).
QSplitter* splitter = new QSplitter();
QWidget* leftWidget = new QWidget();
QVBoxLayout* leftLayout = new QVBoxLayout();
leftLayout->addWidget(m_sliceDependencyTree);
leftWidget->setLayout(leftLayout);
QWidget* rightWidget = new QWidget();
QVBoxLayout* rightLayout = new QVBoxLayout();
rightLayout->addWidget(m_sliceDependentsTree);
rightWidget->setLayout(rightLayout);
splitter->addWidget(leftWidget);
splitter->addWidget(rightWidget);
QList<int> sizes;
const int totalWidth = size().width();
const int firstColumnSize = totalWidth / 2;
sizes << firstColumnSize << (totalWidth - firstColumnSize);
splitter->setSizes(sizes);
splitter->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
QHBoxLayout* bottomLegendAndButtonsLayout = new QHBoxLayout();
// Create/populate button box.
{
QDialogButtonBox* buttonBox = new QDialogButtonBox(this);
QPushButton* browseButton = new QPushButton(tr("Browse..."));
browseButton->setToolTip(tr("Browse for a slice whose relationships you want to see"));
browseButton->setDefault(false);
browseButton->setAutoDefault(false);
buttonBox->addButton(browseButton, QDialogButtonBox::ActionRole);
connect(browseButton, &QPushButton::clicked, this, &SliceRelationshipWidget::OnBrowseClicked);
QPushButton* currentlySelectedEntity = new QPushButton(tr("Current Entity"));
currentlySelectedEntity->setToolTip(tr("Inspect slice relationships for the currently selected entity"));
currentlySelectedEntity->setDefault(false);
currentlySelectedEntity->setAutoDefault(false);
buttonBox->addButton(currentlySelectedEntity, QDialogButtonBox::ActionRole);
connect(currentlySelectedEntity, &QPushButton::clicked, this, &SliceRelationshipWidget::OnInspectSelectedEntity);
bottomLegendAndButtonsLayout->addWidget(buttonBox, 1);
}
m_bottomLayout = new QVBoxLayout();
m_bottomLayout->setAlignment(Qt::AlignBottom);
m_bottomLayout->addLayout(bottomLegendAndButtonsLayout);
// Add everything to main layout.
layout->addWidget(splitter, 1);
layout->addLayout(m_bottomLayout, 0);
setLayout(layout);
connect(m_sliceDependentsTree, &QTreeWidget::itemDoubleClicked, this, &SliceRelationshipWidget::OnSliceAssetDrilledDown);
connect(m_sliceDependencyTree, &QTreeWidget::itemDoubleClicked, this, &SliceRelationshipWidget::OnSliceAssetDrilledDown);
SliceDependencyBrowserNotificationsBus::Handler::BusConnect();
SliceRelationshipRequestBus::Handler::BusConnect();
}
SliceRelationshipWidget::~SliceRelationshipWidget()
{
SliceDependencyBrowserNotificationsBus::Handler::BusDisconnect();
SliceRelationshipRequestBus::Handler::BusDisconnect();
}
void SliceRelationshipWidget::OnSliceRelationshipModelUpdated(const AZStd::shared_ptr<SliceRelationshipNode>& focusNode)
{
GenerateTreesForNode(focusNode);
}
void SliceRelationshipWidget::OnSliceRelationshipViewRequested(const AZ::Data::AssetId& assetId)
{
ResetTrees(assetId);
}
QTreeWidgetItem* AddRootItem(QTreeWidget* widget, const QString& name)
{
QTreeWidgetItem* item = new QTreeWidgetItem(widget);
item->setText(0, name);
item->setExpanded(true);
widget->addTopLevelItem(item);
return item;
}
QTreeWidgetItem* AddChildItem(QTreeWidgetItem* parent, const QString& name)
{
QTreeWidgetItem* item = new QTreeWidgetItem(parent);
item->setText(0, name);
parent->addChild(item);
return item;
}
bool SliceRelationshipWidget::CheckForCycle(QTreeWidgetItem* parentItem, QString searchFor)
{
while (parentItem)
{
if (parentItem->text(0) == searchFor)
{
return true;
}
parentItem = parentItem->parent();
}
return false;
}
void SliceRelationshipWidget::GenerateDependentsTree(const AZStd::shared_ptr<SliceRelationshipNode>& node, QTreeWidgetItem* parentItem)
{
const SliceRelationshipNode::SliceRelationshipNodeSet& dependentNodes = node->GetDependents();
for (const auto& dependentNode : dependentNodes)
{
// before we add this item, we need to make sure that there is no PARENT item (including 'parentItem') that already
// includes the child node, to detect cycles.
QString childItemName = QString((dependentNode->GetSliceRelativePath()).c_str());
if (CheckForCycle(parentItem, childItemName))
{
childItemName = QString(SliceRelationshipWidgetInternal::s_cycleDetectedFormatter).arg(childItemName);
QTreeWidgetItem* childItem = AddChildItem(parentItem, childItemName);
childItem->setIcon(0, QIcon(SliceRelationshipWidgetInternal::s_cycleDetectedIcon));
}
else
{
QTreeWidgetItem* childItem = AddChildItem(parentItem, childItemName);
GenerateDependentsTree(dependentNode, childItem);
}
}
}
void SliceRelationshipWidget::GenerateDependenciesTree(const AZStd::shared_ptr<SliceRelationshipNode>& node, QTreeWidgetItem* parentItem)
{
const SliceRelationshipNode::SliceRelationshipNodeSet& dependencyNodes = node->GetDependencies();
for (const auto& dependencyNode : dependencyNodes)
{
QString childItemName = QString((dependencyNode->GetSliceRelativePath()).c_str());
if (CheckForCycle(parentItem, childItemName))
{
childItemName = QString(SliceRelationshipWidgetInternal::s_cycleDetectedFormatter).arg(childItemName);
QTreeWidgetItem* childItem = AddChildItem(parentItem, childItemName);
childItem->setIcon(0, QIcon(SliceRelationshipWidgetInternal::s_cycleDetectedIcon));
}
else
{
QTreeWidgetItem* childItem = AddChildItem(parentItem, childItemName);
GenerateDependenciesTree(dependencyNode, childItem);
}
}
}
void SliceRelationshipWidget::OnBrowseClicked()
{
AzToolsFramework::AssetBrowser::AssetSelectionModel selection = AzToolsFramework::AssetBrowser::AssetSelectionModel::AssetTypeSelection("Slice");
AzToolsFramework::EditorRequests::Bus::Broadcast(&AzToolsFramework::EditorRequests::BrowseForAssets, selection);
if (selection.IsValid())
{
auto product = azrtti_cast<const ProductAssetBrowserEntry*>(selection.GetResult());
AZ_Assert(product, "Incorrect asset type selected. Expected product.");
ResetTrees(product->GetAssetId());
}
}
void SliceRelationshipWidget::OnInspectSelectedEntity()
{
AzToolsFramework::EntityIdList selectedEntities;
AzToolsFramework::ToolsApplicationRequests::Bus::BroadcastResult(selectedEntities, &AzToolsFramework::ToolsApplicationRequests::GetSelectedEntities);
if(!selectedEntities.empty())
{
ResetTrees(selectedEntities.front());
}
}
void SliceRelationshipWidget::OnSliceAssetDrilledDown(QTreeWidgetItem* item, int column)
{
if (item && column >= 0)
{
ResetTrees(AZStd::string(item->text(column).toUtf8().constData()));
}
}
void SliceRelationshipWidget::ResetTrees(const AZ::EntityId& entityId)
{
if (entityId.IsValid())
{
AZ::SliceComponent::SliceInstanceAddress entitySliceAddress;
EBUS_EVENT_ID_RESULT(entitySliceAddress, entityId, AzFramework::EntityIdContextQueryBus, GetOwningSlice);
if (entitySliceAddress.IsValid())
{
ResetTrees((entitySliceAddress.GetReference())->GetSliceAsset().GetId());
}
}
}
void SliceRelationshipWidget::ResetTrees(const AZStd::string& assetRelativePath)
{
AZStd::shared_ptr<SliceRelationshipNode> node = nullptr;
AzToolsFramework::SliceDependencyBrowserRequestsBus::BroadcastResult(node, &AzToolsFramework::SliceDependencyBrowserRequests::ReportSliceAssetDependenciesByPath, assetRelativePath);
GenerateTreesForNode(node);
}
void SliceRelationshipWidget::ResetTrees(const AZ::Data::AssetId& assetId)
{
AZStd::shared_ptr<SliceRelationshipNode> node = nullptr;
AzToolsFramework::SliceDependencyBrowserRequestsBus::BroadcastResult(node ,&AzToolsFramework::SliceDependencyBrowserRequests::ReportSliceAssetDependenciesById, assetId);
GenerateTreesForNode(node);
}
void SliceRelationshipWidget::GenerateTreesForNode(const AZStd::shared_ptr<SliceRelationshipNode>& node)
{
m_sliceDependentsTree->clear();
m_sliceDependencyTree->clear();
if (node != nullptr)
{
// Dependents tree
GenerateDependentsTree(node, AddRootItem(m_sliceDependentsTree, QString((node->GetSliceRelativePath()).c_str())));
// Dependencies tree
GenerateDependenciesTree(node, AddRootItem(m_sliceDependencyTree, QString((node->GetSliceRelativePath()).c_str())));
}
}
} // namespace AzToolsFramework
#include <UI/Slice/SliceRelationshipWidget.moc>
|
/* Copyright 2015 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.
==============================================================================*/
#define EIGEN_USE_THREADS
#include <algorithm>
#include <cmath>
#include "tensorflow/core/framework/numeric_op.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/kernels/depthwise_conv_op.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/work_sharder.h"
#if GOOGLE_CUDA
#include "tensorflow/core/platform/stream_executor.h"
#endif // GOOGLE_CUDA
namespace tensorflow {
// Gradient operations for depthwise convolution.
typedef Eigen::ThreadPoolDevice CPUDevice;
typedef Eigen::GpuDevice GPUDevice;
// Common code between the two backward pass kernels: verifies that the
// dimensions all match and extract the padded rows and columns.
#define EXTRACT_AND_VERIFY_DIMENSIONS(label) \
const Tensor& out_backprop = context->input(2); \
OP_REQUIRES( \
context, input_shape.dims() == 4, \
errors::InvalidArgument(label, ": input must be 4-dimensional")); \
OP_REQUIRES( \
context, filter_shape.dims() == 4, \
errors::InvalidArgument(label, ": filter must be 4-dimensional")); \
OP_REQUIRES( \
context, out_backprop.dims() == 4, \
errors::InvalidArgument(label, ": out_backprop must be 4-dimensional")); \
const int64 batch = input_shape.dim_size(0); \
OP_REQUIRES( \
context, batch == out_backprop.dim_size(0), \
errors::InvalidArgument( \
label, ": input and out_backprop must have the same batch size")); \
const int64 input_rows = input_shape.dim_size(1); \
const int64 input_cols = input_shape.dim_size(2); \
const int64 filter_rows = filter_shape.dim_size(0); \
const int64 filter_cols = filter_shape.dim_size(1); \
const int64 output_rows = out_backprop.dim_size(1); \
const int64 output_cols = out_backprop.dim_size(2); \
const int64 in_depth = input_shape.dim_size(3); \
OP_REQUIRES(context, in_depth == filter_shape.dim_size(2), \
errors::InvalidArgument( \
label, ": input and filter must have the same in_depth")); \
const int64 depth_multiplier = filter_shape.dim_size(3); \
const int64 out_depth = out_backprop.dim_size(3); \
OP_REQUIRES( \
context, (depth_multiplier * in_depth) == out_depth, \
errors::InvalidArgument( \
label, ": depth_multiplier * in_depth not equal to out_depth")); \
const auto stride = strides_[1]; \
int out_rows = 0, out_cols = 0, pad_rows = 0, pad_cols = 0; \
if (filter_cols == filter_rows && filter_rows == 1 && stride == 1) { \
out_rows = input_rows; \
out_cols = input_cols; \
} else { \
OP_REQUIRES_OK( \
context, Get2dOutputSize(input_rows, input_cols, filter_rows, \
filter_cols, stride, stride, padding_, \
&out_rows, &out_cols, &pad_rows, &pad_cols)); \
} \
OP_REQUIRES( \
context, output_rows == out_rows, \
errors::InvalidArgument( \
label, ": Number of rows of out_backprop doesn't match computed: ", \
"actual = ", output_rows, ", computed = ", out_rows)); \
OP_REQUIRES( \
context, output_cols == out_cols, \
errors::InvalidArgument( \
label, ": Number of cols of out_backprop doesn't match computed: ", \
"actual = ", output_cols, ", computed = ", out_cols)); \
DepthwiseArgs args; \
args.batch = batch; \
args.in_rows = input_rows; \
args.in_cols = input_cols; \
args.in_depth = in_depth; \
args.filter_rows = filter_rows; \
args.filter_cols = filter_cols; \
args.depth_multiplier = depth_multiplier; \
args.stride = stride; \
args.pad_rows = pad_rows; \
args.pad_cols = pad_cols; \
args.out_rows = out_rows; \
args.out_cols = out_cols; \
args.out_depth = out_depth; \
VLOG(2) << "DepthwiseConv2d: " << label << " Input: [" << batch << ", " \
<< input_rows << ", " << input_cols << ", " << in_depth \
<< "]; Filter: [" << filter_rows << ", " << filter_cols << ", " \
<< in_depth << ", " << depth_multiplier << "]; stride = " << stride \
<< ", pad_rows = " << pad_rows << ", pad_cols = " << pad_cols \
<< ", output: [" << batch << ", " << out_rows << ", " << out_cols \
<< ", " << out_depth << "]";
// Copies data from local region in 'out_backprop' into 'buffer'.
// The local region coordinates are calculated as the set of output points which
// used the input point ('in_r', 'in_'c') as input during the forward pass.
// Rather than spatially reversing the filter, the input is reversed during
// the copy. The copied data is padded to vector register-width boundaries so
// that it is aligned for efficient traversal and vector multiply-add by the
// depthwise input kernel.
//
// EX:
// in_depth = 3, depth_multiplier = 2, filter [2, 2], register_width = 4
//
// 'out_backprop': [batch, out_rows, out_cols, out_depth]
//
// [a00, a01, a10, a11] [a20, a21, b00, b01]
// [b10, b11, b20, b21] [...]
// [e00, e01, e10, e11] [e20, e21, f00, f01]
// [f10, f11, f20, f21] [...]
//
// 'buffer' (register boundaries shown):
//
// [f00, f01, f10, f11] [f20, f21, 0, 0] in_row = 0, in_col = 0
// [e00, e01, e10, e11] [e20, e21, 0, 0] in_row = 0, in_col = 1
// [b00, b01, b10, b11] [b20, b21, 0, 0] in_row = 1, in_col = 0
// [a00, a01, a10, a11] [a20, a21, 0, 0] in_row = 1, in_col = 1
//
template <typename T>
static void CopyOutputBackpropRegion(const DepthwiseArgs& args,
const int64 padded_filter_inner_dim_size,
const int64 in_r, const int64 in_c,
const T* out_backprop, T* buffer) {
typedef typename Eigen::internal::packet_traits<T>::type Packet;
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
const int64 stride = args.stride;
const int64 filter_rows = args.filter_rows;
const int64 filter_cols = args.filter_cols;
const int64 pad_rows = args.pad_rows;
const int64 pad_cols = args.pad_cols;
const int64 out_rows = args.out_rows;
const int64 out_cols = args.out_cols;
// Calculate the output spatial region which used point (in_r, in_c) as input.
const int64 out_r_start = std::max(
static_cast<int64>(0), (in_r - filter_rows + pad_rows + stride) / stride);
const int64 out_r_end = std::min(out_rows - 1, (in_r + pad_rows) / stride);
const int64 out_c_start = std::max(
static_cast<int64>(0), (in_c - filter_cols + pad_cols + stride) / stride);
const int64 out_c_end = std::min(out_cols - 1, (in_c + pad_cols) / stride);
// Zero-pad 'buffer' if output region is smaller than filter spatial size.
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
if ((out_r_end - out_r_start + 1) < args.filter_rows ||
(out_c_end - out_c_start + 1) < args.filter_cols) {
memset(buffer, 0,
filter_spatial_size * padded_filter_inner_dim_size * sizeof(T));
}
// Calculate vectorized and scalar (residual) lengths for 'in_depth'.
const int64 vectorized_size = (args.out_depth / kPacketSize) * kPacketSize;
const int64 scalar_size = args.out_depth % kPacketSize;
const int64 pad_size = scalar_size > 0 ? kPacketSize - scalar_size : 0;
for (int out_r = out_r_start; out_r <= out_r_end; ++out_r) {
const int64 f_r = in_r + pad_rows - out_r * stride;
for (int out_c = out_c_start; out_c <= out_c_end; ++out_c) {
const int64 f_c = in_c + pad_cols - out_c * stride;
const int64 buf_base =
(f_r * filter_cols + f_c) * padded_filter_inner_dim_size;
// Calculate index into 'out_backprop' for coordinate (out_r, out_c).
auto* out_bprop =
out_backprop + (out_r * args.out_cols + out_c) * args.out_depth;
// Copy vectorized portion of inner dimension into 'buffer'.
for (int64 d = 0; d < vectorized_size; d += kPacketSize) {
auto v = Eigen::internal::ploadu<Packet>(out_bprop + d);
Eigen::internal::pstoreu<T>(buffer + buf_base + d, v);
}
// Copy scalar portion of out_bprop to 'buffer'
for (int64 d = 0; d < scalar_size; ++d) {
buffer[buf_base + vectorized_size + d] = out_bprop[vectorized_size + d];
}
// Pad to vector-register width (if needed).
for (int64 d = 0; d < pad_size; ++d) {
buffer[buf_base + vectorized_size + scalar_size + d] = 0;
}
}
}
}
// Computes the vectorized product of 'buffer' and 'filter' and stores
// result in 'output' at location computed from 'in_r' and 'in_c'.
// If depth_multiplier is > 1, the intermediate output is reduced along
// the depth_multiplier dimension.
//
// EX:
// in_depth = 3, depth_multiplier = 2, filter [2, 2], register_width = 4
// Both 'input_buffer' and 'filter' are padded to register-width boundaries.
//
// 'buffer' [rows, cols, in_depth, depth_multiplier]
//
// [f00, f01, f10, f11] [f20, f21, 0, 0] in_row = 0, in_col = 0
// [e00, e01, e10, e11] [e20, e21, 0, 0] in_row = 0, in_col = 1
// [b00, b01, b10, b11] [b20, b21, 0, 0] in_row = 1, in_col = 0
// [a00, a01, a10, a11] [a20, a21, 0, 0] in_row = 1, in_col = 1
//
// filter [rows, cols, in_depth, depth_multiplier]
// [u0, v0, w0, x0] [y0, z0, 0, 0] [u1, v1, w1, x1] [y1, z1, 0, 0]
// [u2, v2, w2, x2] [y2, z2, 0, 0] [u3, v3, w3, x3] [y3, z3, 0, 0]
//
// First output register [in_depth, depth_multiplier]
// [q00, q01, q10, q11] = ([f00, f01, f10, f11] x [u0, v0, w0, x0]) +
// ([e00, e01, e10, e11] x [u1, v1, w1, x1]) +
// ([b00, b01, b10, b11] x [u2, v2, w2, x2]) +
// ([a00, a01, a10, a11] x [u3, v3, w3, x3])
//
// Reduction step along depth-multiplier dimension:
//
// [q00, q01, q10, q11] [q20, q21, 0, 0] -> [r0, r1, r2, 0]
//
template <typename T>
static void ComputeBackpropInput(const DepthwiseArgs& args,
const int64 padded_filter_inner_dim_size,
const int64 in_r, const int64 in_c,
const T* filter, const T* buffer,
T* out_buffer, T* output) {
typedef typename Eigen::internal::packet_traits<T>::type Packet;
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
const int64 in_depth = args.in_depth;
const int64 depth_multiplier = args.depth_multiplier;
const int64 out_depth = args.out_depth;
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
// Calculate vectorized and scalar lengths of 'out_depth'.
const int64 output_vectorized_size = (out_depth / kPacketSize) * kPacketSize;
const int64 output_scalar_size = out_depth % kPacketSize;
// Calculate base index at which to begin writing output.
const int64 base_output_index = (in_r * args.in_cols + in_c) * in_depth;
// Calculate vectorized and scalar lengths for 'depth_multiplier'. This is
// used to efficiently reduce output when 'depth_multiplier' > kPacketSize.
const int64 dm_vectorized_size =
(depth_multiplier / kPacketSize) * kPacketSize;
const int64 dm_scalar_size = depth_multiplier % kPacketSize;
for (int i = 0; i < output_vectorized_size; i += kPacketSize) {
// Reset accumulator.
auto vaccum = Eigen::internal::pset1<Packet>(0);
for (int j = 0; j < filter_spatial_size; ++j) {
// Calculate index.
const int64 index = i + j * padded_filter_inner_dim_size;
// Load filter.
const auto filter_block = Eigen::internal::ploadu<Packet>(filter + index);
// Load input.
const auto data_block = Eigen::internal::ploadu<Packet>(buffer + index);
// Vector multiply-add.
vaccum = Eigen::internal::pmadd<Packet>(filter_block, data_block, vaccum);
}
if (depth_multiplier == 1) {
// Write directly to the output.
Eigen::internal::pstoreu<T>(output + base_output_index + i, vaccum);
} else {
// Buffer output for subsequent reduction step.
Eigen::internal::pstoreu<T>(out_buffer + i, vaccum);
}
}
if (output_scalar_size > 0) {
auto vaccum = Eigen::internal::pset1<Packet>(0);
for (int j = 0; j < filter_spatial_size; ++j) {
const int64 index =
output_vectorized_size + j * padded_filter_inner_dim_size;
const auto filter_block = Eigen::internal::ploadu<Packet>(filter + index);
const auto data_block = Eigen::internal::ploadu<Packet>(buffer + index);
vaccum = Eigen::internal::pmadd<Packet>(filter_block, data_block, vaccum);
}
// Load accumulator into an array and loop through output.
T out_buf[kPacketSize];
Eigen::internal::pstoreu<T>(out_buf, vaccum);
if (depth_multiplier == 1) {
// Write directly to the output.
for (int j = 0; j < output_scalar_size; ++j) {
output[base_output_index + output_vectorized_size + j] = out_buf[j];
}
} else {
// Buffer output for subsequent reduction step.
for (int j = 0; j < output_scalar_size; ++j) {
out_buffer[output_vectorized_size + j] = out_buf[j];
}
}
}
// Iterate over 'in_depth', reduce over 'depth_multiplier', write 'output'.
if (depth_multiplier > 1) {
for (int64 d = 0; d < in_depth; ++d) {
const int64 index = d * args.depth_multiplier;
T accum = 0;
for (int64 dm = 0; dm < dm_vectorized_size; dm += kPacketSize) {
const auto v = Eigen::internal::ploadu<Packet>(out_buffer + index + dm);
accum += Eigen::internal::predux(v);
}
// Copy scalar portion of replicated output.
for (int64 dm = 0; dm < dm_scalar_size; ++dm) {
accum += out_buffer[index + dm_vectorized_size + dm];
}
// Copy to output.
output[base_output_index + d] = accum;
}
}
}
// Kernels to compute the input backprop for depthwise convolution.
template <typename Device, typename T>
struct LaunchDepthwiseConvBackpropInputOp;
// Computes the depthwise conv2d backprop input of 'out_backprop' by
// 'depthwise_filter' and stores the result in 'in_backprop'.
template <typename T>
struct LaunchDepthwiseConvBackpropInputOp<CPUDevice, T> {
typedef typename Eigen::internal::packet_traits<T>::type Packet;
static void launch(OpKernelContext* ctx, const DepthwiseArgs& args,
const T* out_backprop, const T* depthwise_filter,
T* in_backprop) {
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
// Pad 'depthwise_filter' to vector register width (if needed).
const bool pad_filter = (args.out_depth % kPacketSize) == 0 ? false : true;
Tensor padded_filter;
if (pad_filter) {
// Allocate space for padded filter.
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
const int64 padded_filter_inner_dim_size =
((args.out_depth + kPacketSize - 1) / kPacketSize) * kPacketSize;
OP_REQUIRES_OK(
ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({filter_spatial_size,
padded_filter_inner_dim_size}),
&padded_filter));
// Write out padded filter.
functor::DepthwiseFilterPadOp<T>()(
args, depthwise_filter, padded_filter.template flat<T>().data());
}
const T* filter_data =
pad_filter ? padded_filter.template flat<T>().data() : depthwise_filter;
// Computes one shard of depthwise conv2d backprop input.
auto shard = [&ctx, &args, &out_backprop, &filter_data, &in_backprop](
int64 start, int64 limit) {
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
const int64 input_image_size =
args.in_rows * args.in_cols * args.in_depth;
const int64 output_image_size =
args.out_rows * args.out_cols * args.out_depth;
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
const int64 padded_filter_inner_dim_size =
((args.out_depth + kPacketSize - 1) / kPacketSize) * kPacketSize;
// Allocate buffer to copy regions from 'out_backprop'.
Tensor out_bprop_buffer;
OP_REQUIRES_OK(
ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({filter_spatial_size,
padded_filter_inner_dim_size}),
&out_bprop_buffer));
T* out_bprop_buf = out_bprop_buffer.template flat<T>().data();
// Allocate buffer for intermediate results.
Tensor in_bprop_buffer;
OP_REQUIRES_OK(
ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({padded_filter_inner_dim_size}),
&in_bprop_buffer));
T* in_bprop_buf = in_bprop_buffer.template flat<T>().data();
for (int64 b = start; b < limit; ++b) {
for (int64 in_r = 0; in_r < args.in_rows; ++in_r) {
for (int64 in_c = 0; in_c < args.in_cols; ++in_c) {
// Populate 'out_bprop_buf' from local 'out_backprop' region.
CopyOutputBackpropRegion<T>(
args, padded_filter_inner_dim_size, in_r, in_c,
out_backprop + b * output_image_size, out_bprop_buf);
// Compute depthwise backprop input.
ComputeBackpropInput<T>(args, padded_filter_inner_dim_size, in_r,
in_c, filter_data, out_bprop_buf,
in_bprop_buf,
in_backprop + b * input_image_size);
}
}
}
};
const int64 shard_cost = args.in_rows * args.in_cols * args.out_depth;
auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());
Shard(worker_threads.num_threads, worker_threads.workers, args.batch,
shard_cost, shard);
}
};
template <typename T>
static void DepthwiseConvBackpropInputReference(const DepthwiseArgs& args,
const T* out_backprop,
const T* filter,
T* in_backprop) {
// Naive for loop as a reference point without concerns about performance.
for (int b = 0; b < args.batch; ++b) {
for (int in_r = 0; in_r < args.in_rows; ++in_r) {
for (int in_c = 0; in_c < args.in_cols; ++in_c) {
for (int in_d = 0; in_d < args.in_depth; ++in_d) {
T sum = 0;
const int stride = args.stride;
const int out_d_start = in_d * args.depth_multiplier;
const int out_d_end = out_d_start + args.depth_multiplier;
for (int out_d = out_d_start; out_d < out_d_end; ++out_d) {
const int out_r_start = std::max(
0, (in_r - args.filter_rows + args.pad_rows + stride) / stride);
const int out_r_end =
std::min(args.out_rows - 1, (in_r + args.pad_rows) / stride);
for (int out_r = out_r_start; out_r <= out_r_end; ++out_r) {
const int out_c_start = std::max(
0,
(in_c - args.filter_cols + args.pad_cols + stride) / stride);
const int out_c_end =
std::min(args.out_cols - 1, (in_c + args.pad_cols) / stride);
for (int out_c = out_c_start; out_c <= out_c_end; ++out_c) {
int f_r = in_r + args.pad_rows - out_r * stride;
int f_c = in_c + args.pad_cols - out_c * stride;
int filter_dm = out_d - out_d_start;
int out_backprop_offset =
out_d +
args.out_depth *
(out_c + args.out_cols * (out_r + args.out_rows * b));
int filter_offset =
filter_dm +
args.depth_multiplier *
(in_d + args.in_depth * (f_c + args.filter_cols * f_r));
sum +=
out_backprop[out_backprop_offset] * filter[filter_offset];
}
}
}
int in_backprop_offset =
in_d +
args.in_depth * (in_c + args.in_cols * (in_r + args.in_rows * b));
in_backprop[in_backprop_offset] = sum;
}
}
}
}
}
#if GOOGLE_CUDA
template <typename T>
struct DepthwiseConv2dBackpropInputGPULaunch {
static void Run(const GPUDevice& d, const DepthwiseArgs args,
const T* out_backprop, const T* filter, T* in_backprop);
};
template <typename T>
struct LaunchDepthwiseConvBackpropInputOp<GPUDevice, T> {
static void launch(OpKernelContext* ctx, const DepthwiseArgs args,
const T* out_backprop, const T* filter, T* in_backprop) {
const GPUDevice& d = ctx->eigen_device<GPUDevice>();
DepthwiseConv2dBackpropInputGPULaunch<T>().Run(d, args, out_backprop,
filter, in_backprop);
auto stream = ctx->op_device_context()->stream();
OP_REQUIRES(ctx, stream->ok(), errors::Internal("Launch of gpu kernel for "
"DepthwiseConv2dBackpropInp"
"utGPULaunch failed"));
}
};
#endif // GOOGLE_CUDA
// Kernel to compute the input backprop for depthwise convolution.
template <typename Device, class T>
class DepthwiseConv2dNativeBackpropInputOp : public OpKernel {
public:
explicit DepthwiseConv2dNativeBackpropInputOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_));
OP_REQUIRES(context, strides_.size() == 4,
errors::InvalidArgument("Sliding window strides field must "
"specify 4 dimensions"));
OP_REQUIRES(context, strides_[1] == strides_[2],
errors::InvalidArgument(
"Current implementation only supports equal length "
"strides in the row and column dimensions."));
OP_REQUIRES(
context, (strides_[0] == 1 && strides_[3] == 1),
errors::InvalidArgument("Current implementation does not yet support "
"strides in the batch and depth dimensions."));
OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
}
void Compute(OpKernelContext* context) override {
const Tensor& input_sizes = context->input(0);
const Tensor& filter = context->input(1);
OP_REQUIRES(
context, TensorShapeUtils::IsVector(input_sizes.shape()),
errors::InvalidArgument(
"Conv2DBackpropInput: input_sizes input must be 1-dim, not ",
input_sizes.dims()));
TensorShape input_shape;
const int32* in_sizes_data = input_sizes.template flat<int32>().data();
for (int i = 0; i < input_sizes.NumElements(); ++i) {
OP_REQUIRES(context, in_sizes_data[i] >= 0,
errors::InvalidArgument("Dimension ", i,
" of input_sizes must be >= 0"));
input_shape.AddDim(in_sizes_data[i]);
}
const TensorShape& filter_shape = filter.shape();
EXTRACT_AND_VERIFY_DIMENSIONS("DepthwiseConv2DBackpropInput");
Tensor* in_backprop = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, input_shape, &in_backprop));
auto out_backprop_ptr = out_backprop.template flat<T>().data();
auto filter_ptr = filter.template flat<T>().data();
auto in_backprop_ptr = in_backprop->template flat<T>().data();
// If there is nothing to compute, return.
if (input_shape.num_elements() == 0) {
return;
}
LaunchDepthwiseConvBackpropInputOp<Device, T>::launch(
context, args, out_backprop_ptr, filter_ptr, in_backprop_ptr);
}
private:
std::vector<int32> strides_;
Padding padding_;
TF_DISALLOW_COPY_AND_ASSIGN(DepthwiseConv2dNativeBackpropInputOp);
};
REGISTER_KERNEL_BUILDER(Name("DepthwiseConv2dNativeBackpropInput")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T"),
DepthwiseConv2dNativeBackpropInputOp<CPUDevice, float>);
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropInput")
.Device(DEVICE_CPU)
.TypeConstraint<double>("T"),
DepthwiseConv2dNativeBackpropInputOp<CPUDevice, double>);
#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(Name("DepthwiseConv2dNativeBackpropInput")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.HostMemory("input_sizes"),
DepthwiseConv2dNativeBackpropInputOp<GPUDevice, float>);
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropInput")
.Device(DEVICE_GPU)
.TypeConstraint<double>("T")
.HostMemory("input_sizes"),
DepthwiseConv2dNativeBackpropInputOp<GPUDevice, double>);
#endif // GOOGLE_CUDA
// Kernels to compute the gradients of the filters for depthwise convolution.
// Computes filter backprop using 'out_backprop' and 'input_buffer', storing the
// result in 'output_buffer' at an index computed from 'out_r' and 'out_c'.
//
// EX:
// in_depth = 3, depth_multiplier = 2, filter [2, 2], register_width = 4
// Both 'input_buffer' and 'filter' are padded to register-width boundaries.
//
// 'input_buffer' [rows, cols, in_depth, depth_multiplier]
//
// [f00, f01, f10, f11] [f20, f21, 0, 0] in_row = 0, in_col = 0
// [e00, e01, e10, e11] [e20, e21, 0, 0] in_row = 0, in_col = 1
// [b00, b01, b10, b11] [b20, b21, 0, 0] in_row = 1, in_col = 0
// [a00, a01, a10, a11] [a20, a21, 0, 0] in_row = 1, in_col = 1
//
// 'out_backprop' [out_rows, out_cols, in_depth, depth_multiplier]
//
// [q00, q01, q10, q11] [q20, q21, r00, r01]
// [r10, r11, r20, r21] [s00, s01, s10, s11]
// [s20, s21, t00, t01] [t10, t11, t20, a21]
//
// First output register of 'filter_backprop'
// [u0, v0, w0, x0] += ([f00, f01, f10, f11] x [q00, q01, q10, q11])
//
template <typename T>
static void ComputeBackpropFilter(const DepthwiseArgs& args,
const int64 padded_out_depth_size,
const int64 out_r, const int64 out_c,
const T* out_backprop, const T* input_buffer,
T* output_buffer) {
typedef typename Eigen::internal::packet_traits<T>::type Packet;
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
// Calculate vectorized size of 'padded_out_depth_size'.
const int64 out_depth = args.out_depth;
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
const int64 output_vectorized_size =
(padded_out_depth_size / kPacketSize) * kPacketSize;
const int64 base_output_index = (out_r * args.out_cols + out_c) * out_depth;
// Determine whether we can execute fast or slow code path.
const int64 output_image_size =
args.out_rows * args.out_cols * args.out_depth;
const int64 output_last_vector_index =
output_image_size - (filter_spatial_size * padded_out_depth_size);
const bool fast_path = base_output_index <= output_last_vector_index;
if (fast_path) {
// TODO(andydavis) Process multiple inputs in 'input_buffer' so we can
// amortize the cost of 'output_buffer' load store in the loop below.
for (int i = 0; i < output_vectorized_size; i += kPacketSize) {
// Load vector register from 'out_backprop'.
const auto out_bprop_block =
Eigen::internal::ploadu<Packet>(out_backprop + base_output_index + i);
for (int j = 0; j < filter_spatial_size; ++j) {
const int64 index = i + j * padded_out_depth_size;
// Load vector register from 'input_buffer'.
const auto input_block =
Eigen::internal::ploadu<Packet>(input_buffer + index);
// Load output block into vector register.
auto out_block_data = output_buffer + index;
auto out_block = Eigen::internal::ploadu<Packet>(out_block_data);
// Vector multiply-add.
out_block = Eigen::internal::pmadd<Packet>(out_bprop_block, input_block,
out_block);
// Store 'out_block' back to memory.
Eigen::internal::pstoreu<T>(out_block_data, out_block);
}
}
} else {
// Slow path (cant do vector reads from non-padded 'out_backprop'.
for (int i = 0; i < output_vectorized_size; i += kPacketSize) {
// Calculate safe read size from 'out_backprop'.
const int64 out_bprop_index = base_output_index + i;
const int64 out_bprop_limit =
std::min(output_image_size, out_bprop_index + kPacketSize);
T out_buf[kPacketSize];
memset(&out_buf, 0, kPacketSize * sizeof(T));
const int64 scalar_size = out_bprop_limit - out_bprop_index;
for (int64 j = 0; j < scalar_size; ++j) {
out_buf[j] = out_backprop[out_bprop_index + j];
}
// Load vector register from 'out_buf'.
const auto out_bprop_block = Eigen::internal::ploadu<Packet>(out_buf);
for (int j = 0; j < filter_spatial_size; ++j) {
const int64 index = i + j * padded_out_depth_size;
// Load vector register from 'input_buffer'.
const auto input_block =
Eigen::internal::ploadu<Packet>(input_buffer + index);
// Load output block into vector register.
auto out_block_data = output_buffer + index;
auto out_block = Eigen::internal::ploadu<Packet>(out_block_data);
// Vector multiply-add.
out_block = Eigen::internal::pmadd<Packet>(out_bprop_block, input_block,
out_block);
// Store 'out_block' back to memory.
Eigen::internal::pstoreu<T>(out_block_data, out_block);
}
}
}
}
template <typename Device, typename T>
struct LaunchDepthwiseConvBackpropFilterOp;
template <typename T>
struct LaunchDepthwiseConvBackpropFilterOp<CPUDevice, T> {
typedef typename Eigen::internal::packet_traits<T>::type Packet;
static void launch(OpKernelContext* ctx, const DepthwiseArgs& args,
const T* out_backprop, const T* input,
T* filter_backprop) {
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
const int64 padded_out_depth_size =
((args.out_depth + kPacketSize - 1) / kPacketSize) * kPacketSize;
// Allocate output buffers for each image in 'batch' (padded to vector
// register boundaries).
Tensor output_buffer;
OP_REQUIRES_OK(
ctx, ctx->allocate_temp(DataTypeToEnum<T>::value,
TensorShape({args.batch, filter_spatial_size,
padded_out_depth_size}),
&output_buffer));
T* output_buffer_data = output_buffer.template flat<T>().data();
// Computes one shard of depthwise conv2d backprop filter.
auto shard = [&ctx, &args, &out_backprop, &input, &output_buffer_data](
int64 start, int64 limit) {
static const int64 kPacketSize = (sizeof(Packet) / sizeof(T));
const int64 filter_spatial_size = args.filter_rows * args.filter_cols;
const int64 padded_out_depth_size =
((args.out_depth + kPacketSize - 1) / kPacketSize) * kPacketSize;
// Allocate buffer for local input regions.
Tensor input_buffer;
OP_REQUIRES_OK(
ctx, ctx->allocate_temp(
DataTypeToEnum<T>::value,
TensorShape({filter_spatial_size, padded_out_depth_size}),
&input_buffer));
T* input_buffer_data = input_buffer.template flat<T>().data();
const int64 input_image_size =
args.in_rows * args.in_cols * args.in_depth;
const int64 output_image_size =
args.out_rows * args.out_cols * args.out_depth;
const int64 padded_filter_size =
filter_spatial_size * padded_out_depth_size;
for (int b = start; b < limit; ++b) {
// Initialize 'output_buffer' for 'b'.
auto* output_buffer = output_buffer_data + b * padded_filter_size;
memset(output_buffer, 0, padded_filter_size * sizeof(T));
for (int out_r = 0; out_r < args.out_rows; ++out_r) {
for (int out_c = 0; out_c < args.out_cols; ++out_c) {
// Populate 'input_buffer_data' with data from local input region.
functor::DepthwiseInputCopyOp<T>()(
args, padded_out_depth_size, out_r, out_c,
input + b * input_image_size, input_buffer_data);
// Compute depthwise backprop filter.
ComputeBackpropFilter(args, padded_out_depth_size, out_r, out_c,
out_backprop + b * output_image_size,
input_buffer_data, output_buffer);
}
}
}
};
const int64 shard_cost = args.out_rows * args.out_cols * args.out_depth;
auto worker_threads = *(ctx->device()->tensorflow_cpu_worker_threads());
Shard(worker_threads.num_threads, worker_threads.workers, args.batch,
shard_cost, shard);
// Accumulate 'output_buffer' from each shard into 'output'.
const int64 out_depth = args.out_depth;
const int64 vectorized_size = (out_depth / kPacketSize) * kPacketSize;
const int64 scalar_size = out_depth - vectorized_size;
const int64 padded_filter_size =
filter_spatial_size * padded_out_depth_size;
memset(filter_backprop, 0, filter_spatial_size * out_depth * sizeof(T));
for (int64 i = 0; i < filter_spatial_size; ++i) {
const int64 buffer_base = i * padded_out_depth_size;
const int64 output_base = i * out_depth;
// Write vectorized length of filter's inner dimension to output.
for (int64 j = 0; j < vectorized_size; j += kPacketSize) {
// Load data from 'filter_backprop' into vector register.
auto out_block_data = filter_backprop + output_base + j;
auto out_block = Eigen::internal::ploadu<Packet>(out_block_data);
for (int b = 0; b < args.batch; ++b) {
// Load data from 'output_buffer' for 'b'.
const auto* output_buffer =
output_buffer_data + b * padded_filter_size;
const auto v =
Eigen::internal::ploadu<Packet>(output_buffer + buffer_base + j);
// Add 'v' to 'out_block'.
out_block = Eigen::internal::padd<Packet>(out_block, v);
}
// Store 'out_block' back to memory.
Eigen::internal::pstoreu<T>(out_block_data, out_block);
}
// Write scalar length of filter's inner dimension to output.
for (int64 j = 0; j < scalar_size; ++j) {
for (int b = 0; b < args.batch; ++b) {
const auto* output_buffer =
output_buffer_data + b * padded_filter_size;
filter_backprop[output_base + vectorized_size + j] +=
output_buffer[buffer_base + vectorized_size + j];
}
}
}
}
};
template <typename T>
static void DepthwiseConvBackpropFilterReference(const DepthwiseArgs& args,
const T* out_backprop,
const T* input,
T* filter_backprop) {
int num_filter_backprop = args.filter_rows * args.filter_cols *
args.in_depth * args.depth_multiplier;
memset(filter_backprop, 0, num_filter_backprop * sizeof(T));
// Naive for loop as a reference point without concerns about performance.
for (int b = 0; b < args.batch; ++b) {
for (int out_r = 0; out_r < args.out_rows; ++out_r) {
for (int out_c = 0; out_c < args.out_cols; ++out_c) {
for (int out_d = 0; out_d < args.out_depth; ++out_d) {
const int in_d = out_d / args.depth_multiplier;
const int dm = out_d % args.depth_multiplier;
const int in_r_start = out_r * args.stride - args.pad_rows;
const int in_c_start = out_c * args.stride - args.pad_cols;
for (int f_r = 0; f_r < args.filter_rows; ++f_r) {
for (int f_c = 0; f_c < args.filter_cols; ++f_c) {
const int in_r = in_r_start + f_r;
const int in_c = in_c_start + f_c;
if (in_r >= 0 && in_r < args.in_rows && in_c >= 0 &&
in_c < args.in_cols) {
int out_backprop_offset =
out_d +
args.out_depth *
(out_c + args.out_cols * (out_r + args.out_rows * b));
int input_offset =
in_d +
args.in_depth *
(in_c + args.in_cols * (in_r + args.in_rows * b));
int filter_backprop_offset =
dm +
args.depth_multiplier *
(in_d + args.in_depth * (f_c + args.filter_cols * f_r));
filter_backprop[filter_backprop_offset] +=
input[input_offset] * out_backprop[out_backprop_offset];
}
}
}
}
}
}
}
}
#if GOOGLE_CUDA
template <typename T>
struct DepthwiseConv2dBackpropFilterGPULaunch {
static void Run(const GPUDevice& d, const DepthwiseArgs args,
const T* out_backprop, const T* input, T* filter_backprop);
};
template <typename T>
struct LaunchDepthwiseConvBackpropFilterOp<GPUDevice, T> {
static void launch(OpKernelContext* ctx, const DepthwiseArgs args,
const T* out_backprop, const T* input,
T* filter_backprop) {
const GPUDevice& d = ctx->eigen_device<GPUDevice>();
auto stream = ctx->op_device_context()->stream();
// Initialize the results to 0.
int num_filter_backprop =
args.filter_rows * args.filter_cols * args.out_depth;
perftools::gputools::DeviceMemoryBase filter_bp_ptr(filter_backprop,
num_filter_backprop);
stream->ThenMemset32(&filter_bp_ptr, 0, num_filter_backprop * sizeof(T));
DepthwiseConv2dBackpropFilterGPULaunch<T>().Run(d, args, out_backprop,
input, filter_backprop);
OP_REQUIRES(ctx, stream->ok(), errors::Internal("Launch of gpu kernel for "
"DepthwiseConv2dBackpropFil"
"terGPULaunch failed"));
}
};
#endif // GOOGLE_CUDA
// Kernel to compute the filter backprop for depthwise convolution.
template <typename Device, class T>
class DepthwiseConv2dNativeBackpropFilterOp : public OpKernel {
public:
explicit DepthwiseConv2dNativeBackpropFilterOp(OpKernelConstruction* context)
: OpKernel(context) {
OP_REQUIRES_OK(context, context->GetAttr("strides", &strides_));
OP_REQUIRES(context, strides_.size() == 4,
errors::InvalidArgument("Sliding window strides field must "
"specify 4 dimensions"));
OP_REQUIRES(context, strides_[1] == strides_[2],
errors::InvalidArgument(
"Current implementation only supports equal length "
"strides in the row and column dimensions."));
OP_REQUIRES(
context, (strides_[0] == 1 && strides_[3] == 1),
errors::InvalidArgument("Current implementation does not yet support "
"strides in the batch and depth dimensions."));
OP_REQUIRES_OK(context, context->GetAttr("padding", &padding_));
}
void Compute(OpKernelContext* context) override {
const Tensor& input = context->input(0);
const Tensor& filter_sizes = context->input(1);
OP_REQUIRES(
context, TensorShapeUtils::IsVector(filter_sizes.shape()),
errors::InvalidArgument(
"Conv2DBackpropFilter: filter_sizes input must be 1-dim, not ",
filter_sizes.dims()));
TensorShape filter_shape;
const int32* filter_sizes_data = filter_sizes.template flat<int32>().data();
for (int i = 0; i < filter_sizes.NumElements(); ++i) {
OP_REQUIRES(context, filter_sizes_data[i] >= 0,
errors::InvalidArgument("Dimension ", i,
" of filter_sizes must be >= 0"));
filter_shape.AddDim(filter_sizes_data[i]);
}
const TensorShape& input_shape = input.shape();
EXTRACT_AND_VERIFY_DIMENSIONS("DepthwiseConv2DBackpropFilter");
Tensor* filter_backprop = nullptr;
OP_REQUIRES_OK(context,
context->allocate_output(0, filter_shape, &filter_backprop));
auto out_backprop_ptr = out_backprop.template flat<T>().data();
auto input_ptr = input.template flat<T>().data();
auto filter_backprop_ptr = filter_backprop->template flat<T>().data();
// If there is nothing to compute, return.
if (filter_shape.num_elements() == 0) {
return;
}
LaunchDepthwiseConvBackpropFilterOp<Device, T>::launch(
context, args, out_backprop_ptr, input_ptr, filter_backprop_ptr);
}
private:
std::vector<int32> strides_;
Padding padding_;
TF_DISALLOW_COPY_AND_ASSIGN(DepthwiseConv2dNativeBackpropFilterOp);
};
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropFilter")
.Device(DEVICE_CPU)
.TypeConstraint<float>("T"),
DepthwiseConv2dNativeBackpropFilterOp<CPUDevice, float>);
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropFilter")
.Device(DEVICE_CPU)
.TypeConstraint<double>("T"),
DepthwiseConv2dNativeBackpropFilterOp<CPUDevice, double>);
#if GOOGLE_CUDA
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropFilter")
.Device(DEVICE_GPU)
.TypeConstraint<float>("T")
.HostMemory("filter_sizes"),
DepthwiseConv2dNativeBackpropFilterOp<GPUDevice, float>);
REGISTER_KERNEL_BUILDER(
Name("DepthwiseConv2dNativeBackpropFilter")
.Device(DEVICE_GPU)
.TypeConstraint<double>("T")
.HostMemory("filter_sizes"),
DepthwiseConv2dNativeBackpropFilterOp<GPUDevice, double>);
#endif // GOOGLE_CUDA
} // namespace tensorflow
|
InitialiseAll:
lda #0
.assembler_controlhandler
lda #0
.device_controlhandler
lda #0
.interaction_controlhandler
lda #0
.main_controlhandler
lda #0
.string_controlhandler
lda #0
.tokeniser_controlhandler
lda #0
.variable_controlhandler
rts
|
#include "drape_frontend/frontend_renderer.hpp"
#include "drape_frontend/animation/interpolation_holder.hpp"
#include "drape_frontend/animation_system.hpp"
#include "drape_frontend/debug_rect_renderer.hpp"
#include "drape_frontend/drape_measurer.hpp"
#include "drape_frontend/drape_notifier.hpp"
#include "drape_frontend/gui/drape_gui.hpp"
#include "drape_frontend/gui/ruler_helper.hpp"
#include "drape_frontend/message_subclasses.hpp"
#include "drape_frontend/postprocess_renderer.hpp"
#include "drape_frontend/scenario_manager.hpp"
#include "drape_frontend/screen_operations.hpp"
#include "drape_frontend/screen_quad_renderer.hpp"
#include "drape_frontend/user_mark_shapes.hpp"
#include "drape_frontend/visual_params.hpp"
#include "shaders/programs.hpp"
#include "drape/drape_global.hpp"
#include "drape/framebuffer.hpp"
#include "drape/support_manager.hpp"
#include "drape/utils/glyph_usage_tracker.hpp"
#include "drape/utils/gpu_mem_tracker.hpp"
#include "drape/utils/projection.hpp"
#include "indexer/classificator_loader.hpp"
#include "indexer/drawing_rules.hpp"
#include "indexer/map_style_reader.hpp"
#include "indexer/scales.hpp"
#include "geometry/any_rect2d.hpp"
#include "base/assert.hpp"
#include "base/logging.hpp"
#include "base/stl_helpers.hpp"
#include "base/timer.hpp"
#include "std/target_os.hpp"
#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <functional>
#include <limits>
#include <memory>
#include <thread>
#include <utility>
using namespace std::placeholders;
namespace df
{
namespace
{
float constexpr kIsometryAngle = static_cast<float>(math::pi) * 76.0f / 180.0f;
double constexpr kVSyncInterval = 0.06;
// Metal/Vulkan rendering is fast, so we can decrease sync inverval.
double constexpr kVSyncIntervalMetalVulkan = 0.03;
std::string const kTransitBackgroundColor = "TransitBackground";
template <typename ToDo>
bool RemoveGroups(ToDo && filter, std::vector<drape_ptr<RenderGroup>> & groups,
ref_ptr<dp::OverlayTree> tree)
{
auto const itEnd = groups.end();
auto it = std::remove_if(groups.begin(), itEnd, [&filter, tree](drape_ptr<RenderGroup> & group)
{
if (filter(group))
{
group->RemoveOverlay(tree);
return true;
}
return false;
});
if (it != itEnd)
{
groups.erase(it, itEnd);
return true;
}
return false;
}
class DebugLabelGuard
{
public:
DebugLabelGuard(ref_ptr<dp::GraphicsContext> context, std::string const & label)
: m_context(context)
{
m_context->PushDebugLabel(label);
}
~DebugLabelGuard()
{
m_context->PopDebugLabel();
}
private:
ref_ptr<dp::GraphicsContext> m_context;
};
#if defined(DEBUG) || defined(DEBUG_DRAPE_XCODE)
#define DEBUG_LABEL(context, labelText) DebugLabelGuard __debugLabel(context, labelText);
#else
#define DEBUG_LABEL(context, labelText)
#endif
class DrapeMeasurerGuard
{
public:
DrapeMeasurerGuard()
{
DrapeMeasurer::Instance().BeforeRenderFrame();
}
~DrapeMeasurerGuard()
{
DrapeMeasurer::Instance().AfterRenderFrame(m_isActiveFrame, m_viewportCenter);
}
void SetProperties(bool isActiveFrame, m2::PointD const & viewportCenter)
{
m_isActiveFrame = isActiveFrame;
m_viewportCenter = viewportCenter;
}
private:
bool m_isActiveFrame = false;
m2::PointD m_viewportCenter = m2::PointD::Zero();
};
#if defined(DRAPE_MEASURER_BENCHMARK) && (defined(RENDER_STATISTIC) || defined(TRACK_GPU_MEM))
class DrapeImmediateRenderingMeasurerGuard
{
public:
DrapeImmediateRenderingMeasurerGuard(ref_ptr<dp::GraphicsContext> context)
: m_context(context)
{
DrapeMeasurer::Instance().BeforeImmediateRendering();
}
~DrapeImmediateRenderingMeasurerGuard()
{
DrapeMeasurer::Instance().AfterImmediateRendering();
#ifdef DISABLE_SCREEN_PRESENTATION
m_context->DebugSynchronizeWithCPU();
#endif
}
private:
ref_ptr<dp::GraphicsContext> m_context;
};
#endif
} // namespace
FrontendRenderer::FrontendRenderer(Params && params)
: BaseRenderer(ThreadsCommutator::RenderThread, params)
, m_trafficRenderer(new TrafficRenderer())
, m_transitSchemeRenderer(new TransitSchemeRenderer())
, m_drapeApiRenderer(new DrapeApiRenderer())
, m_overlayTree(new dp::OverlayTree(VisualParams::Instance().GetVisualScale()))
, m_enablePerspectiveInNavigation(false)
, m_enable3dBuildings(params.m_allow3dBuildings)
, m_isIsometry(false)
, m_blockTapEvents(params.m_blockTapEvents)
, m_choosePositionMode(false)
, m_screenshotMode(params.m_myPositionParams.m_hints.m_screenshotMode)
, m_viewport(params.m_viewport)
, m_modelViewChangedHandler(std::move(params.m_modelViewChangedHandler))
, m_tapEventInfoHandler(std::move(params.m_tapEventHandler))
, m_userPositionChangedHandler(std::move(params.m_positionChangedHandler))
, m_userPositionPendingTimeoutHandler(std::move(params.m_userPositionPendingTimeoutHandler))
, m_requestedTiles(params.m_requestedTiles)
, m_maxGeneration(0)
, m_maxUserMarksGeneration(0)
, m_needRestoreSize(false)
, m_trafficEnabled(params.m_trafficEnabled)
, m_overlaysTracker(new OverlaysTracker())
, m_overlaysShowStatsCallback(std::move(params.m_overlaysShowStatsCallback))
, m_forceUpdateScene(false)
, m_forceUpdateUserMarks(false)
, m_postprocessRenderer(new PostprocessRenderer())
, m_enabledOnStartEffects(params.m_enabledEffects)
#ifdef SCENARIO_ENABLE
, m_scenarioManager(new ScenarioManager(this))
#endif
, m_notifier(make_unique_dp<DrapeNotifier>(params.m_commutator))
{
#ifdef DEBUG
m_isTeardowned = false;
#endif
ASSERT(m_modelViewChangedHandler, ());
ASSERT(m_tapEventInfoHandler, ());
ASSERT(m_userPositionChangedHandler, ());
ASSERT(m_userPositionPendingTimeoutHandler, ());
m_gpsTrackRenderer = make_unique_dp<GpsTrackRenderer>([this](uint32_t pointsCount)
{
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<CacheCirclesPackMessage>(
pointsCount, CacheCirclesPackMessage::GpsTrack),
MessagePriority::Normal);
});
m_routeRenderer = make_unique_dp<RouteRenderer>([this](uint32_t pointsCount)
{
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<CacheCirclesPackMessage>(
pointsCount, CacheCirclesPackMessage::RoutePreview),
MessagePriority::Normal);
});
m_myPositionController = make_unique_dp<MyPositionController>(
std::move(params.m_myPositionParams), make_ref(m_notifier));
StartThread();
}
FrontendRenderer::~FrontendRenderer()
{
ASSERT(m_isTeardowned, ());
}
void FrontendRenderer::Teardown()
{
m_scenarioManager.reset();
StopThread();
#ifdef DEBUG
m_isTeardowned = true;
#endif
}
void FrontendRenderer::UpdateCanBeDeletedStatus()
{
m2::RectD const & screenRect = m_userEventStream.GetCurrentScreen().ClipRect();
std::vector<m2::RectD> notFinishedTileRects;
notFinishedTileRects.reserve(m_notFinishedTiles.size());
for (auto const & tileKey : m_notFinishedTiles)
notFinishedTileRects.push_back(tileKey.GetGlobalRect());
for (RenderLayer & layer : m_layers)
{
for (auto & group : layer.m_renderGroups)
{
if (!group->IsPendingOnDelete())
continue;
bool canBeDeleted = true;
if (!notFinishedTileRects.empty())
{
m2::RectD const tileRect = group->GetTileKey().GetGlobalRect();
if (tileRect.IsIntersect(screenRect))
canBeDeleted = !HasIntersection(tileRect, notFinishedTileRects);
}
layer.m_isDirty |= group->UpdateCanBeDeletedStatus(canBeDeleted, m_currentZoomLevel,
make_ref(m_overlayTree));
}
}
}
void FrontendRenderer::AcceptMessage(ref_ptr<Message> message)
{
switch (message->GetType())
{
case Message::Type::FlushTile:
{
ref_ptr<FlushRenderBucketMessage> msg = message;
dp::RenderState const & state = msg->GetState();
TileKey const & key = msg->GetKey();
drape_ptr<dp::RenderBucket> bucket = msg->AcceptBuffer();
if (key.m_zoomLevel == m_currentZoomLevel && CheckTileGenerations(key))
{
PrepareBucket(state, bucket);
AddToRenderGroup<RenderGroup>(state, std::move(bucket), key);
}
break;
}
case Message::Type::FlushOverlays:
{
ref_ptr<FlushOverlaysMessage> msg = message;
TOverlaysRenderData renderData = msg->AcceptRenderData();
for (auto & overlayRenderData : renderData)
{
if (overlayRenderData.m_tileKey.m_zoomLevel == m_currentZoomLevel &&
CheckTileGenerations(overlayRenderData.m_tileKey))
{
PrepareBucket(overlayRenderData.m_state, overlayRenderData.m_bucket);
AddToRenderGroup<RenderGroup>(overlayRenderData.m_state, std::move(overlayRenderData.m_bucket),
overlayRenderData.m_tileKey);
}
}
UpdateCanBeDeletedStatus();
m_firstTilesReady = true;
if (m_firstLaunchAnimationTriggered)
{
CheckAndRunFirstLaunchAnimation();
m_firstLaunchAnimationTriggered = false;
}
break;
}
case Message::Type::FinishTileRead:
{
ref_ptr<FinishTileReadMessage> msg = message;
bool changed = false;
for (auto const & tileKey : msg->GetTiles())
{
if (CheckTileGenerations(tileKey))
{
auto it = m_notFinishedTiles.find(tileKey);
if (it != m_notFinishedTiles.end())
{
m_notFinishedTiles.erase(it);
changed = true;
}
}
}
if (changed || m_notFinishedTiles.empty())
UpdateCanBeDeletedStatus();
if (m_notFinishedTiles.empty())
{
#if defined(DRAPE_MEASURER_BENCHMARK) && defined(GENERATING_STATISTIC)
DrapeMeasurer::Instance().EndScenePreparing();
#endif
m_trafficRenderer->OnGeometryReady(m_currentZoomLevel);
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
if (m_graphicsStage == GraphicsStage::WaitReady)
m_graphicsStage = GraphicsStage::WaitRendering;
#endif
}
break;
}
case Message::Type::InvalidateRect:
{
ref_ptr<InvalidateRectMessage> m = message;
InvalidateRect(m->GetRect());
break;
}
case Message::Type::FlushUserMarks:
{
ref_ptr<FlushUserMarksMessage> msg = message;
TUserMarksRenderData marksRenderData = msg->AcceptRenderData();
for (auto & renderData : marksRenderData)
{
if (renderData.m_tileKey.m_zoomLevel == m_currentZoomLevel &&
CheckTileGenerations(renderData.m_tileKey))
{
PrepareBucket(renderData.m_state, renderData.m_bucket);
AddToRenderGroup<UserMarkRenderGroup>(renderData.m_state, std::move(renderData.m_bucket),
renderData.m_tileKey);
}
}
break;
}
case Message::Type::GuiLayerRecached:
{
ref_ptr<GuiLayerRecachedMessage> msg = message;
CHECK(m_context != nullptr, ());
drape_ptr<gui::LayerRenderer> renderer = std::move(msg->AcceptRenderer());
renderer->Build(m_context, make_ref(m_gpuProgramManager));
if (msg->NeedResetOldGui())
m_guiRenderer.reset();
if (m_guiRenderer == nullptr)
m_guiRenderer = std::move(renderer);
else
m_guiRenderer->Merge(make_ref(renderer));
CHECK(m_guiRenderer != nullptr, ());
m_guiRenderer->SetLayout(m_lastWidgetsLayout);
bool oldMode = m_choosePositionMode;
m_choosePositionMode = m_guiRenderer->HasWidget(gui::WIDGET_CHOOSE_POSITION_MARK);
if (oldMode != m_choosePositionMode)
{
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
CheckIsometryMinScale(screen);
UpdateDisplacementEnabled();
m_forceUpdateScene = true;
}
if (m_guiRenderer->HasWidget(gui::WIDGET_RULER))
gui::DrapeGui::GetRulerHelper().Invalidate();
break;
}
case Message::Type::GuiLayerLayout:
{
m_lastWidgetsLayout = ref_ptr<GuiLayerLayoutMessage>(message)->GetLayoutInfo();
if (m_guiRenderer != nullptr)
m_guiRenderer->SetLayout(m_lastWidgetsLayout);
break;
}
case Message::Type::UpdateMyPositionRoutingOffset:
{
ref_ptr<UpdateMyPositionRoutingOffsetMessage> msg = message;
m_myPositionController->UpdateRoutingOffsetY(msg->UseDefault(), msg->GetOffsetY());
m_myPositionController->UpdatePosition();
break;
}
case Message::Type::MapShapes:
{
ref_ptr<MapShapesMessage> msg = message;
CHECK(m_context != nullptr, ());
m_myPositionController->SetRenderShape(m_context, m_texMng, msg->AcceptShape());
m_selectionShape = msg->AcceptSelection();
if (m_selectObjectMessage != nullptr)
{
ProcessSelection(make_ref(m_selectObjectMessage));
m_selectObjectMessage.reset();
AddUserEvent(make_unique_dp<SetVisibleViewportEvent>(m_userEventStream.GetVisibleViewport()));
}
break;
}
case Message::Type::ChangeMyPositionMode:
{
ref_ptr<ChangeMyPositionModeMessage> msg = message;
switch (msg->GetChangeType())
{
case ChangeMyPositionModeMessage::SwitchNextMode:
m_myPositionController->NextMode(m_userEventStream.GetCurrentScreen());
break;
case ChangeMyPositionModeMessage::StopFollowing:
m_myPositionController->StopLocationFollow();
break;
case ChangeMyPositionModeMessage::LoseLocation:
m_myPositionController->LoseLocation();
break;
default:
ASSERT(false, ("Unknown change type:", static_cast<int>(msg->GetChangeType())));
break;
}
break;
}
case Message::Type::CompassInfo:
{
ref_ptr<CompassInfoMessage> msg = message;
m_myPositionController->OnCompassUpdate(msg->GetInfo(), m_userEventStream.GetCurrentScreen());
break;
}
case Message::Type::GpsInfo:
{
#ifdef SCENARIO_ENABLE
if (m_scenarioManager->IsRunning())
break;
#endif
ref_ptr<GpsInfoMessage> msg = message;
m_myPositionController->OnLocationUpdate(msg->GetInfo(), msg->IsNavigable(),
m_userEventStream.GetCurrentScreen());
location::RouteMatchingInfo const & info = msg->GetRouteInfo();
if (info.HasDistanceFromBegin())
{
m_routeRenderer->UpdateDistanceFromBegin(info.GetDistanceFromBegin());
// Here we have to recache route arrows.
m_routeRenderer->PrepareRouteArrows(m_userEventStream.GetCurrentScreen(),
std::bind(&FrontendRenderer::OnPrepareRouteArrows, this, _1, _2));
}
break;
}
case Message::Type::SelectObject:
{
ref_ptr<SelectObjectMessage> msg = message;
m_overlayTree->SetSelectedFeature(msg->IsDismiss() ? FeatureID() : msg->GetFeatureID());
if (m_selectionShape == nullptr)
{
m_selectObjectMessage = make_unique_dp<SelectObjectMessage>(
msg->GetSelectedObject(), msg->GetPosition(), msg->GetFeatureID(), msg->IsAnim(),
msg->IsGeometrySelectionAllowed(), true /* isSelectionShapeVisible */);
break;
}
ProcessSelection(msg);
AddUserEvent(make_unique_dp<SetVisibleViewportEvent>(m_userEventStream.GetVisibleViewport()));
break;
}
case Message::Type::FlushSelectionGeometry:
{
ref_ptr<FlushSelectionGeometryMessage> msg = message;
if (m_selectionShape != nullptr)
{
m_selectionShape->AddSelectionGeometry(msg->AcceptRenderData(), msg->GetRecacheId());
if (m_selectionShape->HasSelectionGeometry())
{
auto bbox = m_selectionShape->GetSelectionGeometryBoundingBox();
CHECK(bbox.IsValid(), ());
bbox.Scale(kBoundingBoxScale);
AddUserEvent(make_unique_dp<SetRectEvent>(bbox, true /* rotate */, kDoNotChangeZoom,
true /* isAnim */, true /* useVisibleViewport */,
nullptr /* parallelAnimCreator */));
}
}
break;
}
case Message::Type::FlushSubroute:
{
ref_ptr<FlushSubrouteMessage> msg = message;
auto subrouteData = msg->AcceptRenderData();
if (subrouteData->m_recacheId < 0)
subrouteData->m_recacheId = m_lastRecacheRouteId;
if (!CheckRouteRecaching(make_ref(subrouteData)))
break;
m_routeRenderer->ClearObsoleteData(m_lastRecacheRouteId);
CHECK(m_context != nullptr, ());
m_routeRenderer->AddSubrouteData(m_context, std::move(subrouteData), make_ref(m_gpuProgramManager));
// Here we have to recache route arrows.
m_routeRenderer->PrepareRouteArrows(m_userEventStream.GetCurrentScreen(),
std::bind(&FrontendRenderer::OnPrepareRouteArrows, this, _1, _2));
if (m_pendingFollowRoute != nullptr)
{
FollowRoute(m_pendingFollowRoute->m_preferredZoomLevel,
m_pendingFollowRoute->m_preferredZoomLevelIn3d,
m_pendingFollowRoute->m_enableAutoZoom, m_pendingFollowRoute->m_isArrowGlued);
m_pendingFollowRoute.reset();
}
break;
}
case Message::Type::FlushTransitScheme:
{
ref_ptr<FlushTransitSchemeMessage > msg = message;
auto renderData = msg->AcceptRenderData();
CHECK(m_context != nullptr, ());
m_transitSchemeRenderer->AddRenderData(m_context, make_ref(m_gpuProgramManager),
make_ref(m_overlayTree), std::move(renderData));
break;
}
case Message::Type::FlushSubrouteArrows:
{
ref_ptr<FlushSubrouteArrowsMessage> msg = message;
drape_ptr<SubrouteArrowsData> routeArrowsData = msg->AcceptRenderData();
if (CheckRouteRecaching(make_ref(routeArrowsData)))
{
CHECK(m_context != nullptr, ());
m_routeRenderer->AddSubrouteArrowsData(m_context, std::move(routeArrowsData),
make_ref(m_gpuProgramManager));
}
break;
}
case Message::Type::FlushSubrouteMarkers:
{
ref_ptr<FlushSubrouteMarkersMessage> msg = message;
drape_ptr<SubrouteMarkersData> markersData = msg->AcceptRenderData();
if (markersData->m_recacheId < 0)
markersData->m_recacheId = m_lastRecacheRouteId;
if (CheckRouteRecaching(make_ref(markersData)))
{
CHECK(m_context != nullptr, ());
m_routeRenderer->AddSubrouteMarkersData(m_context, std::move(markersData),
make_ref(m_gpuProgramManager));
}
break;
}
case Message::Type::RemoveSubroute:
{
ref_ptr<RemoveSubrouteMessage> msg = message;
if (msg->NeedDeactivateFollowing())
{
CHECK(m_context != nullptr, ());
m_routeRenderer->SetFollowingEnabled(false);
m_routeRenderer->Clear();
++m_lastRecacheRouteId;
m_myPositionController->DeactivateRouting();
m_postprocessRenderer->OnChangedRouteFollowingMode(m_context, false /* active */);
if (m_enablePerspectiveInNavigation)
DisablePerspective();
}
else
{
m_routeRenderer->RemoveSubrouteData(msg->GetSegmentId());
}
break;
}
case Message::Type::FollowRoute:
{
ref_ptr<FollowRouteMessage> const msg = message;
// After night style switching or drape engine reinitialization FrontendRenderer can
// receive FollowRoute message before FlushSubroute message, so we need to postpone its processing.
if (m_routeRenderer->GetSubroutes().empty())
{
m_pendingFollowRoute = std::make_unique<FollowRouteData>(
msg->GetPreferredZoomLevel(), msg->GetPreferredZoomLevelIn3d(), msg->EnableAutoZoom(),
msg->IsArrowGlued());
break;
}
FollowRoute(msg->GetPreferredZoomLevel(), msg->GetPreferredZoomLevelIn3d(),
msg->EnableAutoZoom(), msg->IsArrowGlued());
break;
}
case Message::Type::DeactivateRouteFollowing:
{
m_myPositionController->DeactivateRouting();
CHECK(m_context != nullptr, ());
m_postprocessRenderer->OnChangedRouteFollowingMode(m_context, false /* active */);
if (m_enablePerspectiveInNavigation)
DisablePerspective();
break;
}
case Message::Type::AddRoutePreviewSegment:
{
ref_ptr<AddRoutePreviewSegmentMessage> const msg = message;
RouteRenderer::PreviewInfo info;
info.m_startPoint = msg->GetStartPoint();
info.m_finishPoint = msg->GetFinishPoint();
m_routeRenderer->AddPreviewSegment(msg->GetSegmentId(), std::move(info));
break;
}
case Message::Type::RemoveRoutePreviewSegment:
{
ref_ptr<RemoveRoutePreviewSegmentMessage> const msg = message;
if (msg->NeedRemoveAll())
m_routeRenderer->RemoveAllPreviewSegments();
else
m_routeRenderer->RemovePreviewSegment(msg->GetSegmentId());
break;
}
case Message::Type::SetSubrouteVisibility:
{
ref_ptr<SetSubrouteVisibilityMessage> const msg = message;
m_routeRenderer->SetSubrouteVisibility(msg->GetSubrouteId(), msg->IsVisible());
break;
}
case Message::Type::PrepareSubrouteArrows:
{
ref_ptr<PrepareSubrouteArrowsMessage> msg = message;
m_routeRenderer->CacheRouteArrows(m_userEventStream.GetCurrentScreen(),
msg->GetSubrouteId(), msg->AcceptBorders(),
std::bind(&FrontendRenderer::OnCacheRouteArrows, this, _1, _2));
break;
}
case Message::Type::RecoverContextDependentResources:
{
UpdateContextDependentResources();
break;
}
case Message::Type::UpdateMapStyle:
{
#ifdef BUILD_DESIGNER
classificator::Load();
#endif // BUILD_DESIGNER
// Clear all graphics.
for (RenderLayer & layer : m_layers)
{
layer.m_renderGroups.clear();
layer.m_isDirty = false;
}
// Must be recreated on map style changing.
CHECK(m_context != nullptr, ());
m_transitBackground = make_unique_dp<ScreenQuadRenderer>(m_context);
// Invalidate read manager.
{
BaseBlockingMessage::Blocker blocker;
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<InvalidateReadManagerRectMessage>(blocker),
MessagePriority::Normal);
blocker.Wait();
}
// Delete all messages which can contain render states (and textures references inside).
auto f = [this]()
{
InstantMessageFilter([](ref_ptr<Message> msg) { return msg->ContainsRenderState(); });
};
// Notify backend renderer and wait for completion.
{
BaseBlockingMessage::Blocker blocker;
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<SwitchMapStyleMessage>(blocker, std::move(f)),
MessagePriority::Normal);
blocker.Wait();
}
UpdateContextDependentResources();
break;
}
case Message::Type::AllowAutoZoom:
{
ref_ptr<AllowAutoZoomMessage> const msg = message;
m_myPositionController->EnableAutoZoomInRouting(msg->AllowAutoZoom());
break;
}
case Message::Type::EnablePerspective:
{
AddUserEvent(make_unique_dp<SetAutoPerspectiveEvent>(true /* isAutoPerspective */));
break;
}
case Message::Type::Allow3dMode:
{
ref_ptr<Allow3dModeMessage> const msg = message;
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
#ifdef OMIM_OS_DESKTOP
if (m_enablePerspectiveInNavigation == msg->AllowPerspective() &&
m_enablePerspectiveInNavigation != screen.isPerspective())
{
AddUserEvent(make_unique_dp<SetAutoPerspectiveEvent>(m_enablePerspectiveInNavigation));
}
#endif
if (m_enable3dBuildings != msg->Allow3dBuildings())
{
m_enable3dBuildings = msg->Allow3dBuildings();
CheckIsometryMinScale(screen);
m_forceUpdateScene = true;
}
if (m_enablePerspectiveInNavigation != msg->AllowPerspective())
{
m_enablePerspectiveInNavigation = msg->AllowPerspective();
m_myPositionController->EnablePerspectiveInRouting(m_enablePerspectiveInNavigation);
if (m_myPositionController->IsInRouting())
{
AddUserEvent(make_unique_dp<SetAutoPerspectiveEvent>(m_enablePerspectiveInNavigation));
}
}
break;
}
case Message::Type::FlushCirclesPack:
{
ref_ptr<FlushCirclesPackMessage> msg = message;
CHECK(m_context != nullptr, ());
switch (msg->GetDestination())
{
case CacheCirclesPackMessage::GpsTrack:
m_gpsTrackRenderer->AddRenderData(m_context, make_ref(m_gpuProgramManager), msg->AcceptRenderData());
break;
case CacheCirclesPackMessage::RoutePreview:
m_routeRenderer->AddPreviewRenderData(m_context, msg->AcceptRenderData(), make_ref(m_gpuProgramManager));
break;
}
break;
}
case Message::Type::UpdateGpsTrackPoints:
{
ref_ptr<UpdateGpsTrackPointsMessage> msg = message;
m_gpsTrackRenderer->UpdatePoints(msg->GetPointsToAdd(), msg->GetPointsToRemove());
break;
}
case Message::Type::ClearGpsTrackPoints:
{
m_gpsTrackRenderer->Clear();
break;
}
case Message::Type::BlockTapEvents:
{
ref_ptr<BlockTapEventsMessage> msg = message;
m_blockTapEvents = msg->NeedBlock();
break;
}
case Message::Type::SetKineticScrollEnabled:
{
ref_ptr<SetKineticScrollEnabledMessage> msg = message;
m_userEventStream.SetKineticScrollEnabled(msg->IsEnabled());
break;
}
case Message::Type::OnEnterForeground:
{
ref_ptr<OnEnterForegroundMessage> msg = message;
m_myPositionController->OnEnterForeground(msg->GetTime());
break;
}
case Message::Type::OnEnterBackground:
{
m_myPositionController->OnEnterBackground();
break;
}
case Message::Type::SetAddNewPlaceMode:
{
ref_ptr<SetAddNewPlaceModeMessage> msg = message;
m_userEventStream.SetKineticScrollEnabled(msg->IsKineticScrollEnabled());
m_dragBoundArea = msg->AcceptBoundArea();
if (msg->IsEnabled())
{
if (!m_dragBoundArea.empty())
{
PullToBoundArea(true /* randomPlace */, true /* applyZoom */);
}
else
{
m2::PointD const pt = msg->HasPosition()? msg->GetPosition() :
m_userEventStream.GetCurrentScreen().GlobalRect().Center();
int zoom = kDoNotChangeZoom;
if (m_currentZoomLevel < scales::GetAddNewPlaceScale())
zoom = scales::GetAddNewPlaceScale();
AddUserEvent(make_unique_dp<SetCenterEvent>(pt, zoom, true /* isAnim */, false /* trackVisibleViewport */,
nullptr /* parallelAnimCreator */));
}
}
break;
}
case Message::Type::SetVisibleViewport:
{
ref_ptr<SetVisibleViewportMessage> msg = message;
AddUserEvent(make_unique_dp<SetVisibleViewportEvent>(msg->GetRect()));
m_myPositionController->SetVisibleViewport(msg->GetRect());
m_myPositionController->UpdatePosition();
PullToBoundArea(false /* randomPlace */, false /* applyZoom */);
break;
}
case Message::Type::Invalidate:
{
m_myPositionController->ResetRoutingNotFollowTimer();
m_myPositionController->ResetBlockAutoZoomTimer();
break;
}
case Message::Type::EnableTransitScheme:
{
ref_ptr<EnableTransitSchemeMessage > msg = message;
m_transitSchemeEnabled = msg->IsEnabled();
#ifndef OMIM_OS_IPHONE_SIMULATOR
CHECK(m_context != nullptr, ());
m_postprocessRenderer->SetEffectEnabled(m_context, PostprocessRenderer::Effect::Antialiasing,
msg->IsEnabled() || m_isAntialiasingEnabled);
#endif
if (!msg->IsEnabled())
m_transitSchemeRenderer->ClearContextDependentResources(make_ref(m_overlayTree));
break;
}
case Message::Type::ClearTransitSchemeData:
{
ref_ptr<ClearTransitSchemeDataMessage> msg = message;
m_transitSchemeRenderer->Clear(msg->GetMwmId(), make_ref(m_overlayTree));
break;
}
case Message::Type::ClearAllTransitSchemeData:
{
m_transitSchemeRenderer->ClearContextDependentResources(make_ref(m_overlayTree));
break;
}
case Message::Type::EnableTraffic:
{
ref_ptr<EnableTrafficMessage> msg = message;
m_trafficEnabled = msg->IsTrafficEnabled();
if (msg->IsTrafficEnabled())
m_forceUpdateScene = true;
else
m_trafficRenderer->ClearContextDependentResources();
break;
}
case Message::Type::RegenerateTraffic:
case Message::Type::SetSimplifiedTrafficColors:
case Message::Type::UpdateMetalines:
case Message::Type::EnableIsolines:
{
m_forceUpdateScene = true;
break;
}
case Message::Type::EnableDebugRectRendering:
{
ref_ptr<EnableDebugRectRenderingMessage> msg = message;
m_isDebugRectRenderingEnabled = msg->IsEnabled();
m_debugRectRenderer->SetEnabled(msg->IsEnabled());
}
break;
case Message::Type::InvalidateUserMarks:
{
m_forceUpdateUserMarks = true;
break;
}
case Message::Type::FlushTrafficData:
{
if (!m_trafficEnabled)
break;
ref_ptr<FlushTrafficDataMessage> msg = message;
CHECK(m_context != nullptr, ());
m_trafficRenderer->AddRenderData(m_context, make_ref(m_gpuProgramManager),
msg->AcceptRenderData());
break;
}
case Message::Type::ClearTrafficData:
{
ref_ptr<ClearTrafficDataMessage> msg = message;
m_trafficRenderer->Clear(msg->GetMwmId());
break;
}
case Message::Type::DrapeApiFlush:
{
ref_ptr<DrapeApiFlushMessage> msg = message;
CHECK(m_context != nullptr, ());
m_drapeApiRenderer->AddRenderProperties(m_context, make_ref(m_gpuProgramManager),
msg->AcceptProperties());
break;
}
case Message::Type::DrapeApiRemove:
{
ref_ptr<DrapeApiRemoveMessage> msg = message;
if (msg->NeedRemoveAll())
m_drapeApiRenderer->Clear();
else
m_drapeApiRenderer->RemoveRenderProperty(msg->GetId());
break;
}
case Message::Type::SetTrackedFeatures:
{
ref_ptr<SetTrackedFeaturesMessage> msg = message;
m_overlaysTracker->SetTrackedOverlaysFeatures(msg->AcceptFeatures());
m_forceUpdateScene = true;
break;
}
case Message::Type::SetPostprocessStaticTextures:
{
ref_ptr<SetPostprocessStaticTexturesMessage> msg = message;
m_postprocessRenderer->SetStaticTextures(msg->AcceptTextures());
break;
}
case Message::Type::SetPosteffectEnabled:
{
ref_ptr<SetPosteffectEnabledMessage> msg = message;
if (msg->GetEffect() == PostprocessRenderer::Effect::Antialiasing)
m_isAntialiasingEnabled = msg->IsEnabled();
#ifndef OMIM_OS_IPHONE_SIMULATOR
CHECK(m_context != nullptr, ());
m_postprocessRenderer->SetEffectEnabled(m_context, msg->GetEffect(), msg->IsEnabled());
#endif
break;
}
case Message::Type::RunFirstLaunchAnimation:
{
ref_ptr<RunFirstLaunchAnimationMessage> msg = message;
m_firstLaunchAnimationTriggered = true;
CheckAndRunFirstLaunchAnimation();
break;
}
case Message::Type::PostUserEvent:
{
ref_ptr<PostUserEventMessage> msg = message;
AddUserEvent(msg->AcceptEvent());
break;
}
case Message::Type::FinishTexturesInitialization:
{
ref_ptr<FinishTexturesInitializationMessage> msg = message;
m_finishTexturesInitialization = true;
break;
}
case Message::Type::CleanupTextures:
{
// Do nothing, just destroy message with textures.
break;
}
case Message::Type::ShowDebugInfo:
{
ref_ptr<ShowDebugInfoMessage> msg = message;
gui::DrapeGui::Instance().GetScaleFpsHelper().SetVisible(msg->IsShown());
break;
}
case Message::Type::NotifyRenderThread:
{
ref_ptr<NotifyRenderThreadMessage> msg = message;
msg->InvokeFunctor();
break;
}
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
case Message::Type::NotifyGraphicsReady:
{
ref_ptr<NotifyGraphicsReadyMessage> msg = message;
m_graphicsReadyFn = msg->GetCallback();
if (m_graphicsReadyFn)
{
m_graphicsStage = GraphicsStage::WaitReady;
if (m_notFinishedTiles.empty())
{
if (msg->NeedInvalidate())
InvalidateRect(m_userEventStream.GetCurrentScreen().ClipRect());
else
m_graphicsStage = GraphicsStage::WaitRendering;
}
}
break;
}
#endif
default:
ASSERT(false, ());
}
}
std::unique_ptr<threads::IRoutine> FrontendRenderer::CreateRoutine()
{
return std::make_unique<Routine>(*this);
}
void FrontendRenderer::UpdateContextDependentResources()
{
++m_lastRecacheRouteId;
for (auto const & subroute : m_routeRenderer->GetSubroutes())
{
auto msg = make_unique_dp<AddSubrouteMessage>(subroute.m_subrouteId,
subroute.m_subroute,
m_lastRecacheRouteId);
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread, std::move(msg),
MessagePriority::Normal);
}
m_trafficRenderer->ClearContextDependentResources();
// In some cases UpdateContextDependentResources can be called before the rendering of
// the first frame. m_currentZoomLevel will be equal to -1, so ResolveTileKeys
// could not be called.
if (m_currentZoomLevel > 0)
{
// Request new tiles.
ScreenBase screen = m_userEventStream.GetCurrentScreen();
m_lastReadedModelView = screen;
m_requestedTiles->Set(screen, m_isIsometry || screen.isPerspective(),
m_forceUpdateScene, m_forceUpdateUserMarks,
ResolveTileKeys(screen));
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<UpdateReadManagerMessage>(),
MessagePriority::UberHighSingleton);
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<RegenerateTransitMessage>(),
MessagePriority::Normal);
}
m_gpsTrackRenderer->Update();
}
void FrontendRenderer::FollowRoute(int preferredZoomLevel, int preferredZoomLevelIn3d,
bool enableAutoZoom, bool isArrowGlued)
{
m_myPositionController->ActivateRouting(
!m_enablePerspectiveInNavigation ? preferredZoomLevel : preferredZoomLevelIn3d,
enableAutoZoom, isArrowGlued);
if (m_enablePerspectiveInNavigation)
AddUserEvent(make_unique_dp<SetAutoPerspectiveEvent>(true /* isAutoPerspective */));
m_routeRenderer->SetFollowingEnabled(true);
CHECK(m_context != nullptr, ());
m_postprocessRenderer->OnChangedRouteFollowingMode(m_context, true /* active */);
}
bool FrontendRenderer::CheckRouteRecaching(ref_ptr<BaseSubrouteData> subrouteData)
{
return subrouteData->m_recacheId >= m_lastRecacheRouteId;
}
void FrontendRenderer::InvalidateRect(m2::RectD const & gRect)
{
ScreenBase screen = m_userEventStream.GetCurrentScreen();
m2::RectD rect = gRect;
if (rect.Intersect(screen.ClipRect()))
{
// Find tiles to invalidate.
TTilesCollection tiles;
int const dataZoomLevel = ClipTileZoomByMaxDataZoom(m_currentZoomLevel);
CalcTilesCoverage(rect, dataZoomLevel, [this, &rect, &tiles](int tileX, int tileY)
{
TileKey const key(tileX, tileY, m_currentZoomLevel);
if (rect.IsIntersect(key.GetGlobalRect()))
tiles.insert(key);
});
// Remove tiles to invalidate from screen.
auto eraseFunction = [&tiles](drape_ptr<RenderGroup> const & group)
{
return tiles.find(group->GetTileKey()) != tiles.end();
};
for (RenderLayer & layer : m_layers)
{
RemoveGroups(eraseFunction, layer.m_renderGroups, make_ref(m_overlayTree));
layer.m_isDirty = true;
}
// Remove tiles to invalidate from backend renderer.
BaseBlockingMessage::Blocker blocker;
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<InvalidateReadManagerRectMessage>(blocker, tiles),
MessagePriority::High);
blocker.Wait();
// Request new tiles.
m_lastReadedModelView = screen;
m_requestedTiles->Set(screen, m_isIsometry || screen.isPerspective(),
m_forceUpdateScene, m_forceUpdateUserMarks,
ResolveTileKeys(screen));
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<UpdateReadManagerMessage>(),
MessagePriority::UberHighSingleton);
}
}
void FrontendRenderer::OnResize(ScreenBase const & screen)
{
m2::RectD const viewportRect = screen.PixelRectIn3d();
double constexpr kEps = 1e-5;
bool const viewportChanged = !m2::IsEqualSize(m_lastReadedModelView.PixelRectIn3d(), viewportRect, kEps, kEps);
m_myPositionController->OnUpdateScreen(screen);
if (viewportChanged)
m_myPositionController->UpdatePosition();
auto const sx = static_cast<uint32_t>(viewportRect.SizeX());
auto const sy = static_cast<uint32_t>(viewportRect.SizeY());
m_viewport.SetViewport(0, 0, sx, sy);
CHECK(m_context != nullptr, ());
// All resize methods must be protected from setting up the same size.
m_context->Resize(sx, sy);
m_buildingsFramebuffer->SetSize(m_context, sx, sy);
m_postprocessRenderer->Resize(m_context, sx, sy);
m_needRestoreSize = false;
RefreshProjection(screen);
RefreshPivotTransform(screen);
}
template<typename TRenderGroup>
void FrontendRenderer::AddToRenderGroup(dp::RenderState const & state,
drape_ptr<dp::RenderBucket> && renderBucket,
TileKey const & newTile)
{
RenderLayer & layer = m_layers[static_cast<size_t>(GetDepthLayer(state))];
for (auto const & g : layer.m_renderGroups)
{
if (!g->IsPendingOnDelete() && g->GetState() == state && g->GetTileKey().EqualStrict(newTile))
{
g->AddBucket(std::move(renderBucket));
layer.m_isDirty = true;
return;
}
}
drape_ptr<TRenderGroup> group = make_unique_dp<TRenderGroup>(state, newTile);
group->AddBucket(std::move(renderBucket));
layer.m_renderGroups.push_back(move(group));
layer.m_isDirty = true;
}
void FrontendRenderer::RemoveRenderGroupsLater(TRenderGroupRemovePredicate const & predicate)
{
for (RenderLayer & layer : m_layers)
{
RemoveGroups([&predicate, &layer](drape_ptr<RenderGroup> const & group)
{
if (predicate(group))
{
group->DeleteLater();
layer.m_isDirty = true;
return group->CanBeDeleted();
}
return false;
}, layer.m_renderGroups, make_ref(m_overlayTree));
}
}
bool FrontendRenderer::CheckTileGenerations(TileKey const & tileKey)
{
bool const result = (tileKey.m_generation >= m_maxGeneration);
if (tileKey.m_generation > m_maxGeneration)
m_maxGeneration = tileKey.m_generation;
if (tileKey.m_userMarksGeneration > m_maxUserMarksGeneration)
m_maxUserMarksGeneration = tileKey.m_userMarksGeneration;
RemoveRenderGroupsLater([&tileKey](drape_ptr<RenderGroup> const & group)
{
auto const & groupKey = group->GetTileKey();
return groupKey == tileKey &&
(groupKey.m_generation < tileKey.m_generation ||
(group->IsUserMark() && groupKey.m_userMarksGeneration < tileKey.m_userMarksGeneration));
});
return result;
}
void FrontendRenderer::OnCompassTapped()
{
m_myPositionController->OnCompassTapped();
m_selectionTrackInfo.reset();
}
std::pair<FeatureID, kml::MarkId> FrontendRenderer::GetVisiblePOI(m2::PointD const & pixelPoint)
{
double halfSize = VisualParams::Instance().GetTouchRectRadius();
m2::PointD sizePoint(halfSize, halfSize);
m2::RectD selectRect(pixelPoint - sizePoint, pixelPoint + sizePoint);
return GetVisiblePOI(selectRect);
}
std::pair<FeatureID, kml::MarkId> FrontendRenderer::GetVisiblePOI(m2::RectD const & pixelRect)
{
m2::PointD pt = pixelRect.Center();
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
if (m_overlayTree->IsNeedUpdate())
BuildOverlayTree(screen);
dp::TOverlayContainer selectResult;
auto selectionRect = pixelRect;
constexpr double kTapRectFactor = 0.25; // make tap rect size smaller for extended objects
selectionRect.Scale(kTapRectFactor);
SearchInNonDisplaceableUserMarksLayer(screen, DepthLayer::SearchMarkLayer, selectionRect,
selectResult);
if (selectResult.empty())
m_overlayTree->Select(pixelRect, selectResult);
if (selectResult.empty())
return {FeatureID(), kml::kInvalidMarkId};
double minSquaredDist = std::numeric_limits<double>::infinity();
ref_ptr<dp::OverlayHandle> closestOverlayHandle;
for (ref_ptr<dp::OverlayHandle> const & handle : selectResult)
{
double const curSquaredDist = pt.SquaredLength(handle->GetPivot(screen, screen.isPerspective()));
if (curSquaredDist < minSquaredDist)
{
minSquaredDist = curSquaredDist;
closestOverlayHandle = handle;
}
}
CHECK(closestOverlayHandle, ());
auto const & overlayId = closestOverlayHandle->GetOverlayID();
return {overlayId.m_featureId, overlayId.m_markId};
}
void FrontendRenderer::PullToBoundArea(bool randomPlace, bool applyZoom)
{
if (m_dragBoundArea.empty())
return;
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
m2::PointD const center = screen.GlobalRect().Center();
if (!m2::IsPointInsideTriangles(center, m_dragBoundArea))
{
m2::PointD const dest = randomPlace ? m2::GetRandomPointInsideTriangles(m_dragBoundArea) :
m2::ProjectPointToTriangles(center, m_dragBoundArea);
int zoom = kDoNotChangeZoom;
if (applyZoom && m_currentZoomLevel < scales::GetAddNewPlaceScale())
zoom = scales::GetAddNewPlaceScale();
AddUserEvent(make_unique_dp<SetCenterEvent>(dest, zoom, true /* isAnim */, false /* trackVisibleViewport */,
nullptr /* parallelAnimCreator */));
}
}
void FrontendRenderer::ProcessSelection(ref_ptr<SelectObjectMessage> msg)
{
if (msg->IsDismiss())
{
m_selectionShape->Hide();
if (!m_myPositionController->IsModeChangeViewport() && m_selectionTrackInfo.has_value())
{
AddUserEvent(make_unique_dp<SetAnyRectEvent>(m_selectionTrackInfo->m_startRect,
true /* isAnim */, false /* fitInViewport */,
false /* useVisibleViewport */));
}
m_selectionTrackInfo.reset();
}
else
{
double offsetZ = 0.0;
ScreenBase modelView;
m_userEventStream.GetTargetScreen(modelView);
if (modelView.isPerspective() &&
msg->GetSelectedObject() != SelectionShape::ESelectedObject::OBJECT_TRACK)
{
dp::TOverlayContainer selectResult;
if (m_overlayTree->IsNeedUpdate())
BuildOverlayTree(modelView);
m_overlayTree->Select(msg->GetPosition(), selectResult);
for (ref_ptr<dp::OverlayHandle> const & handle : selectResult)
offsetZ = std::max(offsetZ, handle->GetPivotZ());
}
if (msg->IsSelectionShapeVisible())
m_selectionShape->Show(msg->GetSelectedObject(), msg->GetPosition(), offsetZ, msg->IsAnim());
else
m_selectionShape->Hide();
if (!m_myPositionController->IsModeChangeViewport())
{
m2::PointD startPosition;
if (m_selectionShape->IsVisible(modelView, startPosition))
m_selectionTrackInfo = SelectionTrackInfo(modelView.GlobalRect(), startPosition);
}
if (msg->IsGeometrySelectionAllowed())
{
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<CheckSelectionGeometryMessage>(
msg->GetFeatureID(), m_selectionShape->GetRecacheId()),
MessagePriority::Normal);
}
}
}
void FrontendRenderer::BeginUpdateOverlayTree(ScreenBase const & modelView)
{
if (m_overlayTree->Frame())
m_overlayTree->StartOverlayPlacing(modelView, m_currentZoomLevel);
}
void FrontendRenderer::UpdateOverlayTree(ScreenBase const & modelView, drape_ptr<RenderGroup> & renderGroup)
{
if (m_overlayTree->IsNeedUpdate())
renderGroup->CollectOverlay(make_ref(m_overlayTree));
else
renderGroup->Update(modelView);
}
void FrontendRenderer::EndUpdateOverlayTree()
{
if (m_overlayTree->IsNeedUpdate())
{
m_overlayTree->EndOverlayPlacing();
// Track overlays.
if (m_overlaysTracker->StartTracking(m_currentZoomLevel,
m_myPositionController->IsModeHasPosition(),
m_myPositionController->GetDrawablePosition(),
m_myPositionController->GetHorizontalAccuracy()))
{
for (auto const & handle : m_overlayTree->GetHandlesCache())
{
if (handle->IsVisible())
m_overlaysTracker->Track(handle->GetOverlayID().m_featureId);
}
m_overlaysTracker->FinishTracking();
}
}
}
void FrontendRenderer::RenderScene(ScreenBase const & modelView, bool activeFrame)
{
CHECK(m_context != nullptr, ());
#if defined(DRAPE_MEASURER_BENCHMARK) && (defined(RENDER_STATISTIC) || defined(TRACK_GPU_MEM))
DrapeImmediateRenderingMeasurerGuard drapeMeasurerGuard(m_context);
#endif
if (m_postprocessRenderer->BeginFrame(m_context, modelView, activeFrame))
{
RefreshBgColor();
uint32_t clearBits = dp::ClearBits::ColorBit | dp::ClearBits::DepthBit;
if (m_apiVersion == dp::ApiVersion::OpenGLES2 || m_apiVersion == dp::ApiVersion::OpenGLES3)
clearBits |= dp::ClearBits::StencilBit;
uint32_t storeBits = dp::ClearBits::ColorBit;
if (m_postprocessRenderer->IsEffectEnabled(PostprocessRenderer::Effect::Antialiasing))
{
clearBits |= dp::ClearBits::StencilBit;
storeBits |= dp::ClearBits::StencilBit;
m_context->SetStencilReferenceValue(2 /* write this value to the stencil buffer */);
}
m_context->Clear(clearBits, storeBits);
m_context->ApplyFramebuffer("Static frame");
m_viewport.Apply(m_context);
Render2dLayer(modelView);
RenderUserMarksLayer(modelView, DepthLayer::UserLineLayer);
if (m_buildingsFramebuffer->IsSupported())
{
RenderTrafficLayer(modelView);
if (!HasTransitRouteData())
RenderRouteLayer(modelView);
Render3dLayer(modelView);
}
else
{
Render3dLayer(modelView);
RenderTrafficLayer(modelView);
if (!HasTransitRouteData())
RenderRouteLayer(modelView);
}
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
if (m_selectionShape != nullptr)
{
SelectionShape::ESelectedObject selectedObject = m_selectionShape->GetSelectedObject();
if (selectedObject == SelectionShape::OBJECT_MY_POSITION)
{
ASSERT(m_myPositionController->IsModeHasPosition(), ());
m_selectionShape->SetPosition(m_myPositionController->Position());
m_selectionShape->Render(m_context, make_ref(m_gpuProgramManager), modelView,
m_currentZoomLevel, m_frameValues);
}
else if (selectedObject == SelectionShape::OBJECT_POI)
{
m_selectionShape->Render(m_context, make_ref(m_gpuProgramManager), modelView,
m_currentZoomLevel, m_frameValues);
}
}
{
StencilWriterGuard guard(make_ref(m_postprocessRenderer), m_context);
RenderOverlayLayer(modelView);
}
m_gpsTrackRenderer->RenderTrack(m_context, make_ref(m_gpuProgramManager), modelView, m_currentZoomLevel,
m_frameValues);
if (m_selectionShape != nullptr &&
(m_selectionShape->GetSelectedObject() == SelectionShape::OBJECT_USER_MARK ||
m_selectionShape->GetSelectedObject() == SelectionShape::OBJECT_TRACK))
{
m_selectionShape->Render(m_context, make_ref(m_gpuProgramManager), modelView, m_currentZoomLevel,
m_frameValues);
}
if (HasTransitRouteData())
RenderRouteLayer(modelView);
{
StencilWriterGuard guard(make_ref(m_postprocessRenderer), m_context);
RenderUserMarksLayer(modelView, DepthLayer::UserMarkLayer);
RenderUserMarksLayer(modelView, DepthLayer::RoutingBottomMarkLayer);
RenderUserMarksLayer(modelView, DepthLayer::RoutingMarkLayer);
RenderNonDisplaceableUserMarksLayer(modelView, DepthLayer::SearchMarkLayer);
}
if (!HasRouteData())
RenderTransitSchemeLayer(modelView);
m_drapeApiRenderer->Render(m_context, make_ref(m_gpuProgramManager), modelView, m_frameValues);
for (auto const & arrow : m_overlayTree->GetDisplacementInfo())
m_debugRectRenderer->DrawArrow(m_context, modelView, arrow);
}
if (!m_postprocessRenderer->EndFrame(m_context, make_ref(m_gpuProgramManager), m_viewport))
return;
m_myPositionController->Render(m_context, make_ref(m_gpuProgramManager), modelView, m_currentZoomLevel,
m_frameValues);
if (m_guiRenderer != nullptr && !m_screenshotMode)
{
m_guiRenderer->Render(m_context, make_ref(m_gpuProgramManager), m_myPositionController->IsInRouting(),
modelView);
}
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
if (m_graphicsStage == GraphicsStage::WaitRendering)
m_graphicsStage = GraphicsStage::Rendered;
#endif
}
void FrontendRenderer::Render2dLayer(ScreenBase const & modelView)
{
RenderLayer & layer2d = m_layers[static_cast<size_t>(DepthLayer::GeometryLayer)];
layer2d.Sort(make_ref(m_overlayTree));
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "2D Layer");
for (drape_ptr<RenderGroup> const & group : layer2d.m_renderGroups)
RenderSingleGroup(m_context, modelView, make_ref(group));
}
void FrontendRenderer::PreRender3dLayer(ScreenBase const & modelView)
{
if (!m_buildingsFramebuffer->IsSupported())
return;
RenderLayer & layer = m_layers[static_cast<size_t>(DepthLayer::Geometry3dLayer)];
if (layer.m_renderGroups.empty())
return;
m_context->SetFramebuffer(make_ref(m_buildingsFramebuffer));
m_context->SetClearColor(dp::Color::Transparent());
m_context->Clear(dp::ClearBits::ColorBit | dp::ClearBits::DepthBit, dp::ClearBits::ColorBit /* storeBits */);
m_context->ApplyFramebuffer("Buildings");
m_viewport.Apply(m_context);
layer.Sort(make_ref(m_overlayTree));
for (drape_ptr<RenderGroup> const & group : layer.m_renderGroups)
RenderSingleGroup(m_context, modelView, make_ref(group));
}
void FrontendRenderer::Render3dLayer(ScreenBase const & modelView)
{
RenderLayer & layer = m_layers[static_cast<size_t>(DepthLayer::Geometry3dLayer)];
if (layer.m_renderGroups.empty())
return;
DEBUG_LABEL(m_context, "3D Layer");
if (m_buildingsFramebuffer->IsSupported())
{
float const kOpacity = 0.7f;
m_screenQuadRenderer->RenderTexture(m_context, make_ref(m_gpuProgramManager),
m_buildingsFramebuffer->GetTexture(),
kOpacity);
}
else
{
// Fallback for devices which do not support rendering to the texture.
CHECK(m_context != nullptr, ());
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
layer.Sort(make_ref(m_overlayTree));
for (drape_ptr<RenderGroup> const & group : layer.m_renderGroups)
RenderSingleGroup(m_context, modelView, make_ref(group));
}
}
void FrontendRenderer::RenderOverlayLayer(ScreenBase const & modelView)
{
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "Overlay Layer");
RenderLayer & overlay = m_layers[static_cast<size_t>(DepthLayer::OverlayLayer)];
BuildOverlayTree(modelView);
for (drape_ptr<RenderGroup> & group : overlay.m_renderGroups)
RenderSingleGroup(m_context, modelView, make_ref(group));
if (GetStyleReader().IsCarNavigationStyle())
RenderNavigationOverlayLayer(modelView);
}
void FrontendRenderer::RenderNavigationOverlayLayer(ScreenBase const & modelView)
{
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "Navigation Overlay Layer");
RenderLayer & navOverlayLayer = m_layers[static_cast<size_t>(DepthLayer::NavigationLayer)];
for (auto & group : navOverlayLayer.m_renderGroups)
{
if (group->HasOverlayHandles())
RenderSingleGroup(m_context, modelView, make_ref(group));
}
}
bool FrontendRenderer::HasTransitRouteData() const
{
return m_routeRenderer->HasTransitData();
}
bool FrontendRenderer::HasRouteData() const
{
return m_routeRenderer->HasData();
}
void FrontendRenderer::RenderTransitSchemeLayer(ScreenBase const & modelView)
{
CHECK(m_context != nullptr, ());
if (m_transitSchemeEnabled && m_transitSchemeRenderer->IsSchemeVisible(m_currentZoomLevel))
{
DEBUG_LABEL(m_context, "Transit Scheme");
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
RenderTransitBackground();
m_transitSchemeRenderer->RenderTransit(m_context, make_ref(m_gpuProgramManager), modelView,
make_ref(m_postprocessRenderer), m_frameValues,
make_ref(m_debugRectRenderer));
}
}
void FrontendRenderer::RenderTrafficLayer(ScreenBase const & modelView)
{
CHECK(m_context != nullptr, ());
if (m_trafficRenderer->HasRenderData())
{
DEBUG_LABEL(m_context, "Traffic Layer");
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
m_trafficRenderer->RenderTraffic(m_context, make_ref(m_gpuProgramManager), modelView,
m_currentZoomLevel, 1.0f /* opacity */, m_frameValues);
}
}
void FrontendRenderer::RenderTransitBackground()
{
if (!m_finishTexturesInitialization)
return;
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "Transit Background");
dp::TextureManager::ColorRegion region;
m_texMng->GetColorRegion(df::GetColorConstant(kTransitBackgroundColor), region);
CHECK(region.GetTexture() != nullptr, ("Texture manager is not initialized"));
if (!m_transitBackground->IsInitialized())
m_transitBackground->SetTextureRect(m_context, region.GetTexRect());
m_transitBackground->RenderTexture(m_context, make_ref(m_gpuProgramManager),
region.GetTexture(), 1.0f /* opacity */, false /* invertV */);
}
void FrontendRenderer::RenderRouteLayer(ScreenBase const & modelView)
{
if (HasTransitRouteData())
RenderTransitBackground();
if (m_routeRenderer->HasData() || m_routeRenderer->HasPreviewData())
{
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "Route Layer");
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
m_routeRenderer->RenderRoute(m_context, make_ref(m_gpuProgramManager), modelView,
m_trafficRenderer->HasRenderData(), m_frameValues);
}
}
void FrontendRenderer::RenderUserMarksLayer(ScreenBase const & modelView, DepthLayer layerId)
{
auto & renderGroups = m_layers[static_cast<size_t>(layerId)].m_renderGroups;
if (renderGroups.empty())
return;
CHECK(m_context != nullptr, ());
DEBUG_LABEL(m_context, "User Marks: " + DebugPrint(layerId));
m_context->Clear(dp::ClearBits::DepthBit, dp::kClearBitsStoreAll);
for (drape_ptr<RenderGroup> & group : renderGroups)
RenderSingleGroup(m_context, modelView, make_ref(group));
}
void FrontendRenderer::RenderNonDisplaceableUserMarksLayer(ScreenBase const & modelView,
DepthLayer layerId)
{
auto & layer = m_layers[static_cast<size_t>(layerId)];
layer.Sort(nullptr);
for (drape_ptr<RenderGroup> & group : layer.m_renderGroups)
{
group->SetOverlayVisibility(true);
group->Update(modelView);
}
RenderUserMarksLayer(modelView, layerId);
}
void FrontendRenderer::RenderEmptyFrame()
{
CHECK(m_context != nullptr, ());
if (!m_context->Validate())
return;
if (!m_context->BeginRendering())
return;
m_context->SetFramebuffer(nullptr /* default */);
auto const c = dp::Extract(drule::rules().GetBgColor(1 /* scale */), 255);
m_context->SetClearColor(c);
m_context->Clear(dp::ClearBits::ColorBit, dp::ClearBits::ColorBit /* storeBits */);
m_context->ApplyFramebuffer("Empty frame");
m_viewport.Apply(m_context);
m_context->EndRendering();
m_context->Present();
}
void FrontendRenderer::RenderFrame()
{
DrapeMeasurerGuard drapeMeasurerGuard;
CHECK(m_context != nullptr, ());
if (!m_context->Validate())
{
m_frameData.m_forceFullRedrawNextFrame = true;
m_frameData.m_inactiveFramesCounter = 0;
return;
}
auto & scaleFpsHelper = gui::DrapeGui::Instance().GetScaleFpsHelper();
m_frameData.m_timer.Reset();
ScreenBase const & modelView = ProcessEvents(m_frameData.m_modelViewChanged,
m_frameData.m_viewportChanged);
if (m_frameData.m_viewportChanged || m_needRestoreSize)
OnResize(modelView);
if (!m_context->BeginRendering())
return;
// Check for a frame is active.
bool isActiveFrame = m_frameData.m_modelViewChanged || m_frameData.m_viewportChanged;
if (isActiveFrame)
PrepareScene(modelView);
bool const needUpdateDynamicTextures = m_texMng->UpdateDynamicTextures(m_context);
isActiveFrame |= needUpdateDynamicTextures;
isActiveFrame |= m_userEventStream.IsWaitingForActionCompletion();
isActiveFrame |= InterpolationHolder::Instance().IsActive();
bool isActiveFrameForScene = isActiveFrame || m_frameData.m_forceFullRedrawNextFrame;
if (AnimationSystem::Instance().HasAnimations())
{
isActiveFrameForScene |= AnimationSystem::Instance().HasMapAnimations();
isActiveFrame = true;
}
m_routeRenderer->UpdatePreview(modelView);
#ifdef SHOW_FRAMES_STATS
m_frameData.m_framesOverall += static_cast<uint64_t>(isActiveFrame);
m_frameData.m_framesFast += static_cast<uint64_t>(!isActiveFrameForScene);
#endif
RenderScene(modelView, isActiveFrameForScene);
m_context->EndRendering();
auto const hasForceUpdate = m_forceUpdateScene || m_forceUpdateUserMarks;
isActiveFrame |= hasForceUpdate;
#if defined(SCENARIO_ENABLE)
isActiveFrame = true;
#endif
if (m_frameData.m_modelViewChanged || hasForceUpdate)
UpdateScene(modelView);
InterpolationHolder::Instance().Advance(m_frameData.m_frameTime);
AnimationSystem::Instance().Advance(m_frameData.m_frameTime);
// On the first inactive frame we invalidate overlay tree.
if (!isActiveFrame)
{
if (m_frameData.m_inactiveFramesCounter == 0)
m_overlayTree->InvalidateOnNextFrame();
m_frameData.m_inactiveFramesCounter++;
}
else
{
m_frameData.m_inactiveFramesCounter = 0;
}
bool const canSuspend = m_frameData.m_inactiveFramesCounter > FrameData::kMaxInactiveFrames;
m_frameData.m_forceFullRedrawNextFrame = m_overlayTree->IsNeedUpdate();
if (canSuspend)
{
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
EmitGraphicsReady();
#endif
// Process a message or wait for a message.
// IsRenderingEnabled() can return false in case of rendering disabling and we must prevent
// possibility of infinity waiting in ProcessSingleMessage.
ProcessSingleMessage(IsRenderingEnabled());
m_frameData.m_forceFullRedrawNextFrame = true;
m_frameData.m_timer.Reset();
m_frameData.m_inactiveFramesCounter = 0;
isActiveFrameForScene = false;
}
else
{
auto const syncInverval = (m_apiVersion == dp::ApiVersion::Metal ||
m_apiVersion == dp::ApiVersion::Vulkan)
? kVSyncIntervalMetalVulkan
: kVSyncInterval;
double availableTime;
do
{
if (!ProcessSingleMessage(false /* waitForMessage */))
break;
m_frameData.m_forceFullRedrawNextFrame = true;
m_frameData.m_inactiveFramesCounter = 0;
availableTime = syncInverval - m_frameData.m_timer.ElapsedSeconds();
}
while (availableTime > 0.0);
}
#ifndef DISABLE_SCREEN_PRESENTATION
m_context->Present();
#endif
// Limit fps in following mode.
double constexpr kFrameTime = 1.0 / 30.0;
auto const ft = m_frameData.m_timer.ElapsedSeconds();
if (!canSuspend && ft < kFrameTime && m_myPositionController->IsRouteFollowingActive())
{
auto const ms = static_cast<uint32_t>((kFrameTime - ft) * 1000);
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
m_frameData.m_frameTime = m_frameData.m_timer.ElapsedSeconds();
scaleFpsHelper.SetFrameTime(m_frameData.m_frameTime,
m_frameData.m_inactiveFramesCounter + 1 < FrameData::kMaxInactiveFrames);
m_debugRectRenderer->FinishRendering();
#ifndef DRAPE_MEASURER_BENCHMARK
drapeMeasurerGuard.SetProperties(isActiveFrameForScene, modelView.GetOrg());
#endif
}
void FrontendRenderer::BuildOverlayTree(ScreenBase const & modelView)
{
static std::array<DepthLayer, 4> layers = {DepthLayer::OverlayLayer,
DepthLayer::NavigationLayer,
DepthLayer::RoutingBottomMarkLayer,
DepthLayer::RoutingMarkLayer};
BeginUpdateOverlayTree(modelView);
for (auto const layerId : layers)
{
RenderLayer & overlay = m_layers[static_cast<size_t>(layerId)];
overlay.Sort(make_ref(m_overlayTree));
for (drape_ptr<RenderGroup> & group : overlay.m_renderGroups)
UpdateOverlayTree(modelView, group);
}
if (m_transitSchemeRenderer->IsSchemeVisible(m_currentZoomLevel) && !HasTransitRouteData())
m_transitSchemeRenderer->CollectOverlays(make_ref(m_overlayTree), modelView);
EndUpdateOverlayTree();
}
void FrontendRenderer::PrepareBucket(dp::RenderState const & state, drape_ptr<dp::RenderBucket> & bucket)
{
CHECK(m_context != nullptr, ());
auto program = m_gpuProgramManager->GetProgram(state.GetProgram<gpu::Program>());
auto program3d = m_gpuProgramManager->GetProgram(state.GetProgram3d<gpu::Program>());
bool const isPerspective = m_userEventStream.GetCurrentScreen().isPerspective();
if (isPerspective)
program3d->Bind();
else
program->Bind();
bucket->GetBuffer()->Build(m_context, isPerspective ? program3d : program);
}
void FrontendRenderer::RenderSingleGroup(ref_ptr<dp::GraphicsContext> context,
ScreenBase const & modelView,
ref_ptr<BaseRenderGroup> group)
{
group->UpdateAnimation();
group->Render(context, make_ref(m_gpuProgramManager), modelView, m_frameValues,
make_ref(m_debugRectRenderer));
}
void FrontendRenderer::RefreshProjection(ScreenBase const & screen)
{
auto m = dp::MakeProjection(m_apiVersion, 0.0f, screen.GetWidth(), screen.GetHeight(), 0.0f);
m_frameValues.m_projection = glsl::make_mat4(m.data());
}
void FrontendRenderer::RefreshZScale(ScreenBase const & screen)
{
m_frameValues.m_zScale = static_cast<float>(screen.GetZScale());
}
void FrontendRenderer::RefreshPivotTransform(ScreenBase const & screen)
{
if (screen.isPerspective())
{
math::Matrix<float, 4, 4> transform(screen.Pto3dMatrix());
m_frameValues.m_pivotTransform = glsl::make_mat4(transform.m_data);
}
else if (m_isIsometry)
{
math::Matrix<float, 4, 4> transform(math::Identity<float, 4>());
transform(2, 1) = -1.0f / static_cast<float>(tan(kIsometryAngle));
transform(2, 2) = 1.0f / screen.GetHeight();
if (m_apiVersion == dp::ApiVersion::Metal)
{
transform(3, 2) = transform(3, 2) + 0.5f;
transform(2, 2) = transform(2, 2) * 0.5f;
}
m_frameValues.m_pivotTransform = glsl::make_mat4(transform.m_data);
}
else
{
math::Matrix<float, 4, 4> transform(math::Identity<float, 4>());
m_frameValues.m_pivotTransform = glsl::make_mat4(transform.m_data);
}
}
void FrontendRenderer::RefreshBgColor()
{
auto const scale = std::min(df::GetDrawTileScale(m_userEventStream.GetCurrentScreen()),
scales::GetUpperStyleScale());
auto const color = drule::rules().GetBgColor(scale);
auto const c = dp::Extract(color, 255);
CHECK(m_context != nullptr, ());
m_context->SetClearColor(c);
}
void FrontendRenderer::DisablePerspective()
{
AddUserEvent(make_unique_dp<SetAutoPerspectiveEvent>(false /* isAutoPerspective */));
}
void FrontendRenderer::CheckIsometryMinScale(ScreenBase const & screen)
{
bool const isScaleAllowableIn3d = IsScaleAllowableIn3d(m_currentZoomLevel);
bool const isIsometry = m_enable3dBuildings && !m_choosePositionMode && isScaleAllowableIn3d;
if (m_isIsometry != isIsometry)
{
m_isIsometry = isIsometry;
RefreshPivotTransform(screen);
}
}
void FrontendRenderer::ResolveZoomLevel(ScreenBase const & screen)
{
int const prevZoomLevel = m_currentZoomLevel;
m_currentZoomLevel = GetDrawTileScale(screen);
gui::DrapeGui::Instance().GetScaleFpsHelper().SetScale(m_currentZoomLevel);
if (prevZoomLevel != m_currentZoomLevel)
UpdateCanBeDeletedStatus();
CheckIsometryMinScale(screen);
UpdateDisplacementEnabled();
}
void FrontendRenderer::UpdateDisplacementEnabled()
{
if (m_choosePositionMode)
m_overlayTree->SetDisplacementEnabled(m_currentZoomLevel < scales::GetAddNewPlaceScale());
else
m_overlayTree->SetDisplacementEnabled(true);
}
void FrontendRenderer::OnTap(m2::PointD const & pt, bool isLongTap)
{
if (m_blockTapEvents)
return;
double const halfSize = VisualParams::Instance().GetTouchRectRadius();
m2::PointD sizePoint(halfSize, halfSize);
m2::RectD selectRect(pt - sizePoint, pt + sizePoint);
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
bool isMyPosition = false;
m2::PointD const pxPoint2d = screen.P3dtoP(pt);
m2::PointD mercator = screen.PtoG(pxPoint2d);
if (m_myPositionController->IsModeHasPosition())
{
m2::PointD const pixelPos = screen.PtoP3d(screen.GtoP(m_myPositionController->Position()));
isMyPosition = selectRect.IsPointInside(pixelPos);
if (isMyPosition)
mercator = m_myPositionController->Position();
}
ASSERT(m_tapEventInfoHandler != nullptr, ());
auto [featureId, markId] = GetVisiblePOI(selectRect);
m_tapEventInfoHandler({mercator, isLongTap, isMyPosition, featureId, markId});
}
void FrontendRenderer::OnForceTap(m2::PointD const & pt)
{
// Emulate long tap on force tap.
OnTap(pt, true /* isLongTap */);
}
void FrontendRenderer::OnDoubleTap(m2::PointD const & pt)
{
m_userEventStream.AddEvent(make_unique_dp<ScaleEvent>(2.0 /* scale factor */, pt, true /* animated */));
}
void FrontendRenderer::OnTwoFingersTap()
{
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
m_userEventStream.AddEvent(make_unique_dp<ScaleEvent>(0.5 /* scale factor */, screen.PixelRect().Center(),
true /* animated */));
}
bool FrontendRenderer::OnSingleTouchFiltrate(m2::PointD const & pt, TouchEvent::ETouchType type)
{
// This method can be called before gui renderer initialization.
if (m_guiRenderer == nullptr)
return false;
float const rectHalfSize = df::VisualParams::Instance().GetTouchRectRadius();
m2::RectD r(-rectHalfSize, -rectHalfSize, rectHalfSize, rectHalfSize);
r.SetCenter(pt);
switch(type)
{
case TouchEvent::ETouchType::TOUCH_DOWN:
return m_guiRenderer->OnTouchDown(r);
case TouchEvent::ETouchType::TOUCH_UP:
m_guiRenderer->OnTouchUp(r);
return false;
case TouchEvent::ETouchType::TOUCH_CANCEL:
m_guiRenderer->OnTouchCancel(r);
return false;
case TouchEvent::ETouchType::TOUCH_MOVE:
return false;
}
return false;
}
void FrontendRenderer::OnDragStarted()
{
m_myPositionController->DragStarted();
}
void FrontendRenderer::OnDragEnded(m2::PointD const & distance)
{
m_myPositionController->DragEnded(distance);
PullToBoundArea(false /* randomPlace */, false /* applyZoom */);
m_firstLaunchAnimationInterrupted = true;
}
void FrontendRenderer::OnScaleStarted()
{
m_myPositionController->ScaleStarted();
}
void FrontendRenderer::OnRotated()
{
m_myPositionController->Rotated();
}
void FrontendRenderer::CorrectScalePoint(m2::PointD & pt) const
{
m_myPositionController->CorrectScalePoint(pt);
}
void FrontendRenderer::CorrectGlobalScalePoint(m2::PointD & pt) const
{
m_myPositionController->CorrectGlobalScalePoint(pt);
}
void FrontendRenderer::CorrectScalePoint(m2::PointD & pt1, m2::PointD & pt2) const
{
m_myPositionController->CorrectScalePoint(pt1, pt2);
}
void FrontendRenderer::OnScaleEnded()
{
m_myPositionController->ScaleEnded();
PullToBoundArea(false /* randomPlace */, false /* applyZoom */);
m_firstLaunchAnimationInterrupted = true;
m_selectionTrackInfo.reset();
}
void FrontendRenderer::OnAnimatedScaleEnded()
{
m_myPositionController->ResetBlockAutoZoomTimer();
PullToBoundArea(false /* randomPlace */, false /* applyZoom */);
m_firstLaunchAnimationInterrupted = true;
m_selectionTrackInfo.reset();
}
void FrontendRenderer::OnTouchMapAction(TouchEvent::ETouchType touchType, bool isMapTouch)
{
// Here we block timer on start of touch actions. Timer will be unblocked on
// the completion of touch actions. It helps to prevent the creation of redundant checks.
auto const blockTimer = (touchType == TouchEvent::TOUCH_DOWN || touchType == TouchEvent::TOUCH_MOVE);
m_myPositionController->ResetRoutingNotFollowTimer(blockTimer);
if (isMapTouch)
m_selectionTrackInfo.reset();
}
bool FrontendRenderer::OnNewVisibleViewport(m2::RectD const & oldViewport, m2::RectD const & newViewport,
bool needOffset, m2::PointD & gOffset)
{
if (!needOffset)
{
m_selectionTrackInfo.reset();
return false;
}
gOffset = m2::PointD(0, 0);
if (m_myPositionController->IsModeChangeViewport() || m_selectionShape == nullptr ||
oldViewport == newViewport || !m_selectionTrackInfo.has_value())
{
return false;
}
ScreenBase const & screen = m_userEventStream.GetCurrentScreen();
ScreenBase targetScreen;
AnimationSystem::Instance().GetTargetScreen(screen, targetScreen);
m2::PointD pos;
m2::PointD targetPos;
if (!m_selectionShape->IsVisible(screen, pos) || !m_selectionShape->IsVisible(targetScreen, targetPos))
return false;
m2::RectD rect(pos, pos);
m2::RectD targetRect(targetPos, targetPos);
if (m_selectionShape->HasSelectionGeometry())
{
auto r = m_selectionShape->GetSelectionGeometryBoundingBox();
r.Scale(kBoundingBoxScale);
m2::RectD pixelRect;
pixelRect.Add(screen.PtoP3d(screen.GtoP(r.LeftTop())));
pixelRect.Add(screen.PtoP3d(screen.GtoP(r.RightBottom())));
rect.Inflate(pixelRect.SizeX(), pixelRect.SizeY());
targetRect.Inflate(pixelRect.SizeX(), pixelRect.SizeY());
}
else
{
if (m_overlayTree->IsNeedUpdate())
BuildOverlayTree(screen);
if (!(m_selectionShape->GetSelectedObject() == SelectionShape::OBJECT_POI &&
m_overlayTree->GetSelectedFeatureRect(screen, rect) &&
m_overlayTree->GetSelectedFeatureRect(targetScreen, targetRect)))
{
double const r = m_selectionShape->GetRadius();
rect.Inflate(r, r);
targetRect.Inflate(r, r);
}
double const kOffset = 50 * VisualParams::Instance().GetVisualScale();
rect.Inflate(kOffset, kOffset);
targetRect.Inflate(kOffset, kOffset);
}
if (newViewport.SizeX() < rect.SizeX() || newViewport.SizeY() < rect.SizeY())
return false;
m2::PointD pOffset(0.0, 0.0);
if ((oldViewport.IsIntersect(targetRect) && !newViewport.IsRectInside(rect)) ||
(newViewport.IsRectInside(rect) && m_selectionTrackInfo->m_snapSides != m2::PointI::Zero()))
{
// In case the rect of the selection is [partly] hidden, scroll the map to keep it visible.
// In case the rect of the selection is visible after the map scrolling,
// try to rollback part of that scrolling to return the map to its original position.
if (rect.minX() < newViewport.minX() || m_selectionTrackInfo->m_snapSides.x < 0)
{
pOffset.x = std::max(m_selectionTrackInfo->m_startPos.x - pos.x, newViewport.minX() - rect.minX());
m_selectionTrackInfo->m_snapSides.x = -1;
}
else if (rect.maxX() > newViewport.maxX() || m_selectionTrackInfo->m_snapSides.x > 0)
{
pOffset.x = std::min(m_selectionTrackInfo->m_startPos.x - pos.x, newViewport.maxX() - rect.maxX());
m_selectionTrackInfo->m_snapSides.x = 1;
}
if (rect.minY() < newViewport.minY() || m_selectionTrackInfo->m_snapSides.y < 0)
{
pOffset.y = std::max(m_selectionTrackInfo->m_startPos.y - pos.y, newViewport.minY() - rect.minY());
m_selectionTrackInfo->m_snapSides.y = -1;
}
else if (rect.maxY() > newViewport.maxY() || m_selectionTrackInfo->m_snapSides.y > 0)
{
pOffset.y = std::min(m_selectionTrackInfo->m_startPos.y - pos.y, newViewport.maxY() - rect.maxY());
m_selectionTrackInfo->m_snapSides.y = 1;
}
}
double const ptZ = m_selectionShape->GetPositionZ();
gOffset = screen.PtoG(screen.P3dtoP(pos + pOffset, ptZ)) - screen.PtoG(screen.P3dtoP(pos, ptZ));
return true;
}
TTilesCollection FrontendRenderer::ResolveTileKeys(ScreenBase const & screen)
{
m2::RectD rect = screen.ClipRect();
double const vs = VisualParams::Instance().GetVisualScale();
double const extension = vs * dp::kScreenPixelRectExtension * screen.GetScale();
rect.Inflate(extension, extension);
int const dataZoomLevel = ClipTileZoomByMaxDataZoom(m_currentZoomLevel);
m_notFinishedTiles.clear();
// Request new tiles.
TTilesCollection tiles;
/// @todo Introduce small_set class based on buffer_vector.
buffer_vector<TileKey, 8> tilesToDelete;
auto const result = CalcTilesCoverage(rect, dataZoomLevel,
[this, &rect, &tiles, &tilesToDelete](int tileX, int tileY)
{
TileKey const key(tileX, tileY, m_currentZoomLevel);
if (rect.IsIntersect(key.GetGlobalRect()))
{
tiles.insert(key);
m_notFinishedTiles.insert(key);
}
else
{
tilesToDelete.push_back(key);
}
});
// Remove old tiles.
auto removePredicate = [this, &result, &tilesToDelete](drape_ptr<RenderGroup> const & group)
{
TileKey const & key = group->GetTileKey();
return key.m_zoomLevel == m_currentZoomLevel &&
(key.m_x < result.m_minTileX || key.m_x >= result.m_maxTileX ||
key.m_y < result.m_minTileY || key.m_y >= result.m_maxTileY ||
std::find(tilesToDelete.begin(), tilesToDelete.end(), key) != tilesToDelete.end());
};
for (RenderLayer & layer : m_layers)
layer.m_isDirty |= RemoveGroups(removePredicate, layer.m_renderGroups, make_ref(m_overlayTree));
RemoveRenderGroupsLater([this](drape_ptr<RenderGroup> const & group)
{
return group->GetTileKey().m_zoomLevel != m_currentZoomLevel;
});
m_trafficRenderer->OnUpdateViewport(result, m_currentZoomLevel, tilesToDelete);
#if defined(DRAPE_MEASURER_BENCHMARK) && defined(GENERATING_STATISTIC)
DrapeMeasurer::Instance().StartScenePreparing();
#endif
return tiles;
}
void FrontendRenderer::OnContextDestroy()
{
LOG(LINFO, ("On context destroy."));
// Clear all graphics.
for (RenderLayer & layer : m_layers)
{
layer.m_renderGroups.clear();
layer.m_isDirty = false;
}
m_selectObjectMessage.reset();
m_overlayTree->SetSelectedFeature(FeatureID());
m_overlayTree->SetDebugRectRenderer(nullptr);
m_overlayTree->Clear();
m_guiRenderer.reset();
m_selectionShape.reset();
m_buildingsFramebuffer.reset();
m_screenQuadRenderer.reset();
m_myPositionController->ResetRenderShape();
m_routeRenderer->ClearContextDependentResources();
m_gpsTrackRenderer->ClearRenderData();
m_trafficRenderer->ClearContextDependentResources();
m_drapeApiRenderer->Clear();
m_postprocessRenderer->ClearContextDependentResources();
m_transitSchemeRenderer->ClearContextDependentResources(nullptr /* overlayTree */);
m_transitBackground.reset();
m_debugRectRenderer.reset();
CHECK(m_context != nullptr, ());
m_gpuProgramManager->Destroy(m_context);
m_gpuProgramManager.reset();
// Here we have to erase weak pointer to the context, since it
// can be destroyed after this method.
m_context->DoneCurrent();
m_context = nullptr;
m_needRestoreSize = true;
m_firstTilesReady = false;
m_firstLaunchAnimationInterrupted = false;
m_finishTexturesInitialization = false;
}
void FrontendRenderer::OnContextCreate()
{
LOG(LINFO, ("On context create."));
m_context = make_ref(m_contextFactory->GetDrawContext());
m_contextFactory->WaitForInitialization(m_context.get());
m_context->MakeCurrent();
m_context->Init(m_apiVersion);
// Render empty frame here to avoid black initialization screen.
RenderEmptyFrame();
dp::SupportManager::Instance().Init(m_context);
m_gpuProgramManager = make_unique_dp<gpu::ProgramManager>();
m_gpuProgramManager->Init(m_context);
dp::AlphaBlendingState::Apply(m_context);
m_debugRectRenderer = make_unique_dp<DebugRectRenderer>(
m_context, m_gpuProgramManager->GetProgram(gpu::Program::DebugRect),
m_gpuProgramManager->GetParamsSetter());
m_debugRectRenderer->SetEnabled(m_isDebugRectRenderingEnabled);
m_overlayTree->SetDebugRectRenderer(make_ref(m_debugRectRenderer));
m_overlayTree->SetVisualScale(VisualParams::Instance().GetVisualScale());
// Resources recovering.
m_screenQuadRenderer = make_unique_dp<ScreenQuadRenderer>(m_context);
m_postprocessRenderer->Init(m_context, [this]()
{
CHECK(m_context != nullptr, ());
if (!m_context->Validate())
return false;
m_context->SetFramebuffer(nullptr /* default */);
return true;
},
[this](ScreenBase const & modelView)
{
PreRender3dLayer(modelView);
});
#ifndef OMIM_OS_IPHONE_SIMULATOR
for (auto const & effect : m_enabledOnStartEffects)
m_postprocessRenderer->SetEffectEnabled(m_context, effect, true /* enabled */);
m_enabledOnStartEffects.clear();
if (dp::SupportManager::Instance().IsAntialiasingEnabledByDefault() || m_screenshotMode)
m_postprocessRenderer->SetEffectEnabled(m_context, PostprocessRenderer::Antialiasing, true);
#endif
m_buildingsFramebuffer = make_unique_dp<dp::Framebuffer>(dp::TextureFormat::RGBA8,
true /* depthEnabled */,
false /* stencilEnabled */);
m_buildingsFramebuffer->SetFramebufferFallback([this]()
{
return m_postprocessRenderer->OnFramebufferFallback(m_context);
});
m_transitBackground = make_unique_dp<ScreenQuadRenderer>(m_context);
}
void FrontendRenderer::OnRenderingEnabled()
{
m_overlayTree->InvalidateOnNextFrame();
#ifndef DRAPE_MEASURER_BENCHMARK
DrapeMeasurer::Instance().Start();
#endif
}
void FrontendRenderer::OnRenderingDisabled()
{
#ifndef DRAPE_MEASURER_BENCHMARK
DrapeMeasurer::Instance().Stop();
#endif
}
FrontendRenderer::Routine::Routine(FrontendRenderer & renderer) : m_renderer(renderer) {}
void FrontendRenderer::Routine::Do()
{
LOG(LINFO, ("Start routine."));
gui::DrapeGui::Instance().ConnectOnCompassTappedHandler(std::bind(&FrontendRenderer::OnCompassTapped, &m_renderer));
m_renderer.m_myPositionController->SetListener(ref_ptr<MyPositionController::Listener>(&m_renderer));
m_renderer.m_userEventStream.SetListener(ref_ptr<UserEventStream::Listener>(&m_renderer));
m_renderer.CreateContext();
#if defined(DEBUG) || defined(DEBUG_DRAPE_XCODE) || defined(SCENARIO_ENABLE)
gui::DrapeGui::Instance().GetScaleFpsHelper().SetVisible(true);
#endif
m_renderer.ScheduleOverlayCollecting();
#ifdef SHOW_FRAMES_STATS
m_renderer.m_notifier->Notify(ThreadsCommutator::RenderThread, std::chrono::seconds(5),
true /* repeating */, [this](uint64_t)
{
LOG(LINFO, ("framesOverall =", m_renderer.m_frameData.m_framesOverall,
"framesFast =", m_renderer.m_frameData.m_framesFast));
#ifdef TRACK_GPU_MEM
LOG(LINFO, (dp::GPUMemTracker::Inst().GetMemorySnapshot().ToString()));
#endif
});
#endif
#ifndef DRAPE_MEASURER_BENCHMARK
DrapeMeasurer::Instance().SetApiVersion(m_renderer.m_apiVersion);
DrapeMeasurer::Instance().SetResolution(m2::PointU(m_renderer.m_viewport.GetWidth(),
m_renderer.m_viewport.GetHeight()));
DrapeMeasurer::Instance().SetGpuName(m_renderer.m_context->GetRendererName());
DrapeMeasurer::Instance().Start();
#endif
while (!IsCancelled())
m_renderer.IterateRenderLoop();
#ifndef DRAPE_MEASURER_BENCHMARK
DrapeMeasurer::Instance().Stop(true /* forceProcessRealtimeStats */);
#endif
m_renderer.CollectShowOverlaysEvents();
m_renderer.ReleaseResources();
}
void FrontendRenderer::ReleaseResources()
{
for (RenderLayer & layer : m_layers)
layer.m_renderGroups.clear();
m_guiRenderer.reset();
m_myPositionController.reset();
m_selectionShape.reset();
m_routeRenderer.reset();
m_buildingsFramebuffer.reset();
m_screenQuadRenderer.reset();
m_trafficRenderer.reset();
m_transitSchemeRenderer.reset();
m_postprocessRenderer.reset();
m_transitBackground.reset();
m_gpuProgramManager.reset();
// Here m_context can be nullptr, so call the method
// for the context from the factory.
m_contextFactory->GetDrawContext()->DoneCurrent();
m_context = nullptr;
}
void FrontendRenderer::AddUserEvent(drape_ptr<UserEvent> && event)
{
#ifdef SCENARIO_ENABLE
if (m_scenarioManager->IsRunning() && event->GetType() == UserEvent::EventType::Touch)
return;
#endif
m_userEventStream.AddEvent(std::move(event));
if (IsInInfinityWaiting())
CancelMessageWaiting();
}
void FrontendRenderer::PositionChanged(m2::PointD const & position, bool hasPosition)
{
m_userPositionChangedHandler(position, hasPosition);
}
void FrontendRenderer::PositionPendingTimeout()
{
m_userPositionPendingTimeoutHandler();
}
void FrontendRenderer::ChangeModelView(m2::PointD const & center, int zoomLevel,
TAnimationCreator const & parallelAnimCreator)
{
AddUserEvent(make_unique_dp<SetCenterEvent>(center, zoomLevel, true /* isAnim */,
false /* trackVisibleViewport */,
parallelAnimCreator));
}
void FrontendRenderer::ChangeModelView(double azimuth,
TAnimationCreator const & parallelAnimCreator)
{
AddUserEvent(make_unique_dp<RotateEvent>(azimuth, true /* isAnim */, parallelAnimCreator));
}
void FrontendRenderer::ChangeModelView(m2::RectD const & rect,
TAnimationCreator const & parallelAnimCreator)
{
AddUserEvent(make_unique_dp<SetRectEvent>(rect, true /* rotate */, kDoNotChangeZoom, true /* isAnim */,
false /* useVisibleViewport */, parallelAnimCreator));
}
void FrontendRenderer::ChangeModelView(m2::PointD const & userPos, double azimuth,
m2::PointD const & pxZero, int preferredZoomLevel,
Animation::TAction const & onFinishAction,
TAnimationCreator const & parallelAnimCreator)
{
AddUserEvent(make_unique_dp<FollowAndRotateEvent>(userPos, pxZero, azimuth, preferredZoomLevel,
true, onFinishAction, parallelAnimCreator));
}
void FrontendRenderer::ChangeModelView(double autoScale, m2::PointD const & userPos, double azimuth,
m2::PointD const & pxZero, TAnimationCreator const & parallelAnimCreator)
{
AddUserEvent(make_unique_dp<FollowAndRotateEvent>(userPos, pxZero, azimuth, autoScale, parallelAnimCreator));
}
ScreenBase const & FrontendRenderer::ProcessEvents(bool & modelViewChanged, bool & viewportChanged)
{
ScreenBase const & modelView = m_userEventStream.ProcessEvents(modelViewChanged, viewportChanged);
gui::DrapeGui::Instance().SetInUserAction(m_userEventStream.IsInUserAction());
// Location- or compass-update could have changed model view on the previous frame.
// So we have to check it here.
if (m_lastReadedModelView != modelView)
modelViewChanged = true;
return modelView;
}
void FrontendRenderer::PrepareScene(ScreenBase const & modelView)
{
RefreshZScale(modelView);
RefreshPivotTransform(modelView);
m_myPositionController->OnUpdateScreen(modelView);
m_routeRenderer->PrepareRouteArrows(modelView, std::bind(&FrontendRenderer::OnPrepareRouteArrows, this, _1, _2));
}
void FrontendRenderer::UpdateScene(ScreenBase const & modelView)
{
ResolveZoomLevel(modelView);
m_gpsTrackRenderer->Update();
auto removePredicate = [this](drape_ptr<RenderGroup> const & group)
{
uint32_t const kMaxGenerationRange = 5;
TileKey const & key = group->GetTileKey();
return (group->IsOverlay() && key.m_zoomLevel > m_currentZoomLevel) ||
(m_maxGeneration - key.m_generation > kMaxGenerationRange) ||
(group->IsUserMark() &&
(m_maxUserMarksGeneration - key.m_userMarksGeneration > kMaxGenerationRange));
};
for (RenderLayer & layer : m_layers)
layer.m_isDirty |= RemoveGroups(removePredicate, layer.m_renderGroups, make_ref(m_overlayTree));
if (m_forceUpdateScene || m_forceUpdateUserMarks || m_lastReadedModelView != modelView)
{
EmitModelViewChanged(modelView);
m_lastReadedModelView = modelView;
m_requestedTiles->Set(modelView, m_isIsometry || modelView.isPerspective(),
m_forceUpdateScene, m_forceUpdateUserMarks,
ResolveTileKeys(modelView));
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<UpdateReadManagerMessage>(),
MessagePriority::UberHighSingleton);
m_forceUpdateScene = false;
m_forceUpdateUserMarks = false;
}
}
void FrontendRenderer::EmitModelViewChanged(ScreenBase const & modelView) const
{
m_modelViewChangedHandler(modelView);
}
#if defined(OMIM_OS_MAC) || defined(OMIM_OS_LINUX)
void FrontendRenderer::EmitGraphicsReady()
{
if (m_graphicsStage == GraphicsStage::Rendered)
{
if (m_graphicsReadyFn)
m_graphicsReadyFn();
m_graphicsStage = GraphicsStage::Unknown;
m_graphicsReadyFn = nullptr;
}
}
#endif
void FrontendRenderer::OnPrepareRouteArrows(dp::DrapeID subrouteIndex, std::vector<ArrowBorders> && borders)
{
m_commutator->PostMessage(ThreadsCommutator::RenderThread,
make_unique_dp<PrepareSubrouteArrowsMessage>(subrouteIndex, std::move(borders)),
MessagePriority::Normal);
}
void FrontendRenderer::OnCacheRouteArrows(dp::DrapeID subrouteIndex, std::vector<ArrowBorders> const & borders)
{
m_commutator->PostMessage(ThreadsCommutator::ResourceUploadThread,
make_unique_dp<CacheSubrouteArrowsMessage>(subrouteIndex, borders, m_lastRecacheRouteId),
MessagePriority::Normal);
}
drape_ptr<ScenarioManager> const & FrontendRenderer::GetScenarioManager() const
{
return m_scenarioManager;
}
void FrontendRenderer::CollectShowOverlaysEvents()
{
ASSERT(m_overlaysShowStatsCallback != nullptr, ());
m_overlaysShowStatsCallback(m_overlaysTracker->Collect());
}
void FrontendRenderer::CheckAndRunFirstLaunchAnimation()
{
if (!m_firstTilesReady || m_firstLaunchAnimationInterrupted ||
!m_myPositionController->IsModeHasPosition())
{
return;
}
int constexpr kDesiredZoomLevel = 13;
m2::PointD const pos = m_myPositionController->GetDrawablePosition();
AddUserEvent(make_unique_dp<SetCenterEvent>(pos, kDesiredZoomLevel, true /* isAnim */,
false /* trackVisibleViewport */, nullptr /* parallelAnimCreator */));
}
void FrontendRenderer::ScheduleOverlayCollecting()
{
auto const kCollectingEventsPeriod = std::chrono::seconds(10);
m_notifier->Notify(ThreadsCommutator::RenderThread, kCollectingEventsPeriod,
true /* repeating */, [this](uint64_t)
{
if (m_overlaysTracker->IsValid())
CollectShowOverlaysEvents();
});
}
void FrontendRenderer::SearchInNonDisplaceableUserMarksLayer(ScreenBase const & modelView,
DepthLayer layerId,
m2::RectD const & selectionRect,
dp::TOverlayContainer & result)
{
auto & layer = m_layers[static_cast<size_t>(layerId)];
layer.Sort(nullptr);
for (drape_ptr<RenderGroup> & group : layer.m_renderGroups)
{
group->SetOverlayVisibility(true);
group->Update(modelView);
group->ForEachOverlay(
[&modelView, &result, selectionRect = m2::RectF(selectionRect)](ref_ptr<dp::OverlayHandle> const & h)
{
dp::OverlayHandle::Rects shapes;
h->GetPixelShape(modelView, modelView.isPerspective(), shapes);
for (m2::RectF const & shape : shapes)
{
if (selectionRect.IsIntersect(shape))
{
result.push_back(h);
break;
}
}
});
}
}
void FrontendRenderer::RenderLayer::Sort(ref_ptr<dp::OverlayTree> overlayTree)
{
if (!m_isDirty)
return;
RenderGroupComparator comparator;
std::sort(m_renderGroups.begin(), m_renderGroups.end(), std::ref(comparator));
m_isDirty = comparator.m_pendingOnDeleteFound;
while (!m_renderGroups.empty() && m_renderGroups.back()->CanBeDeleted())
{
if (overlayTree)
m_renderGroups.back()->RemoveOverlay(overlayTree);
m_renderGroups.pop_back();
}
}
// static
m2::AnyRectD TapInfo::GetDefaultTapRect(m2::PointD const & mercator, ScreenBase const & screen)
{
m2::AnyRectD result;
double const halfSize = VisualParams::Instance().GetTouchRectRadius();
screen.GetTouchRect(screen.GtoP(mercator), halfSize, result);
return result;
}
// static
m2::AnyRectD TapInfo::GetBookmarkTapRect(m2::PointD const & mercator, ScreenBase const & screen)
{
static int constexpr kBmTouchPixelIncrease = 20;
m2::AnyRectD result;
double const bmAddition = kBmTouchPixelIncrease * VisualParams::Instance().GetVisualScale();
double const halfSize = VisualParams::Instance().GetTouchRectRadius();
double const pxWidth = halfSize;
double const pxHeight = halfSize + bmAddition;
screen.GetTouchRect(screen.GtoP(mercator) + m2::PointD(0, bmAddition),
pxWidth, pxHeight, result);
return result;
}
// static
m2::AnyRectD TapInfo::GetRoutingPointTapRect(m2::PointD const & mercator, ScreenBase const & screen)
{
static int constexpr kRoutingPointTouchPixelIncrease = 20;
m2::AnyRectD result;
double const bmAddition = kRoutingPointTouchPixelIncrease * VisualParams::Instance().GetVisualScale();
double const halfSize = VisualParams::Instance().GetTouchRectRadius();
screen.GetTouchRect(screen.GtoP(mercator), halfSize + bmAddition, result);
return result;
}
// static
m2::AnyRectD TapInfo::GetPreciseTapRect(m2::PointD const & mercator, double eps)
{
return m2::AnyRectD(mercator, ang::AngleD(0.0) /* angle */, m2::RectD(-eps, -eps, eps, eps));
}
} // namespace df
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r8
push %r9
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_normal_ht+0x1ad26, %r9
dec %r8
mov $0x6162636465666768, %rcx
movq %rcx, %xmm4
and $0xffffffffffffffc0, %r9
movntdq %xmm4, (%r9)
nop
nop
nop
nop
nop
xor %r10, %r10
lea addresses_D_ht+0x49c6, %rsi
lea addresses_WC_ht+0x12996, %rdi
nop
xor $53342, %rbp
mov $9, %rcx
rep movsl
nop
cmp $50296, %rbp
lea addresses_WT_ht+0xa847, %rbp
nop
nop
nop
nop
sub $57505, %r10
movb $0x61, (%rbp)
nop
nop
nop
nop
nop
inc %rbp
lea addresses_WC_ht+0x136de, %rsi
lea addresses_WT_ht+0x1e326, %rdi
nop
cmp %r10, %r10
mov $102, %rcx
rep movsw
nop
nop
nop
cmp $57765, %rsi
lea addresses_WC_ht+0x11b26, %r9
nop
nop
nop
nop
nop
dec %rdi
and $0xffffffffffffffc0, %r9
movntdqa (%r9), %xmm2
vpextrq $1, %xmm2, %rsi
nop
inc %rcx
lea addresses_WT_ht+0x17666, %r10
sub %r9, %r9
mov $0x6162636465666768, %rdi
movq %rdi, (%r10)
sub %rcx, %rcx
lea addresses_WT_ht+0xc326, %rsi
lea addresses_normal_ht+0xc326, %rdi
clflush (%rdi)
add %rdx, %rdx
mov $126, %rcx
rep movsl
nop
nop
sub $63012, %rsi
lea addresses_normal_ht+0xa326, %rsi
lea addresses_D_ht+0x3526, %rdi
nop
nop
nop
xor $25359, %r9
mov $93, %rcx
rep movsq
lfence
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r9
pop %r8
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r13
push %r8
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
// REPMOV
lea addresses_normal+0x811e, %rsi
lea addresses_A+0xa126, %rdi
nop
add %rbx, %rbx
mov $96, %rcx
rep movsb
nop
nop
nop
nop
sub %r8, %r8
// Store
lea addresses_normal+0xd326, %rbx
nop
add %r13, %r13
movl $0x51525354, (%rbx)
nop
nop
nop
nop
nop
dec %rdi
// Faulty Load
lea addresses_normal+0x1ab26, %rdi
nop
nop
inc %rcx
movups (%rdi), %xmm3
vpextrq $1, %xmm3, %r13
lea oracles, %rdi
and $0xff, %r13
shlq $12, %r13
mov (%rdi,%r13,1), %r13
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %r8
pop %r13
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_A', 'congruent': 9, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_normal', 'size': 4, 'AVXalign': False, 'NT': False, 'congruent': 9, 'same': False}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'type': 'addresses_normal', 'size': 16, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': True}}
<gen_prepare_buffer>
{'OP': 'STOR', 'dst': {'type': 'addresses_normal_ht', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 9, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_D_ht', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC_ht', 'congruent': 4, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 1, 'AVXalign': False, 'NT': False, 'congruent': 0, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WC_ht', 'congruent': 3, 'same': False}, 'dst': {'type': 'addresses_WT_ht', 'congruent': 9, 'same': True}}
{'OP': 'LOAD', 'src': {'type': 'addresses_WC_ht', 'size': 16, 'AVXalign': False, 'NT': True, 'congruent': 11, 'same': False}}
{'OP': 'STOR', 'dst': {'type': 'addresses_WT_ht', 'size': 8, 'AVXalign': False, 'NT': False, 'congruent': 6, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_WT_ht', 'congruent': 11, 'same': False}, 'dst': {'type': 'addresses_normal_ht', 'congruent': 10, 'same': False}}
{'OP': 'REPM', 'src': {'type': 'addresses_normal_ht', 'congruent': 7, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}}
{'34': 21829}
34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34 34
*/
|
.global s_prepare_buffers
s_prepare_buffers:
push %r11
push %r12
push %r14
push %r9
push %rax
push %rbp
push %rsi
lea addresses_UC_ht+0x13d4b, %r11
dec %rsi
movl $0x61626364, (%r11)
nop
nop
nop
nop
nop
and %rax, %rax
lea addresses_WT_ht+0x9aab, %rsi
nop
nop
and $3270, %r12
mov $0x6162636465666768, %rbp
movq %rbp, (%rsi)
nop
nop
nop
cmp %r11, %r11
lea addresses_WT_ht+0x39b3, %r12
nop
nop
nop
and %rbp, %rbp
vmovups (%r12), %ymm4
vextracti128 $0, %ymm4, %xmm4
vpextrq $0, %xmm4, %r9
cmp %rsi, %rsi
lea addresses_D_ht+0x1ade3, %rax
nop
nop
nop
xor %r14, %r14
movb (%rax), %r11b
nop
nop
nop
nop
cmp $52267, %r11
lea addresses_D_ht+0x1dde3, %r12
nop
nop
add %rsi, %rsi
mov $0x6162636465666768, %rbp
movq %rbp, (%r12)
nop
nop
nop
nop
nop
cmp $5707, %r14
pop %rsi
pop %rbp
pop %rax
pop %r9
pop %r14
pop %r12
pop %r11
ret
.global s_faulty_load
s_faulty_load:
push %r11
push %rax
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
// Load
lea addresses_D+0x199e3, %rcx
nop
nop
nop
nop
nop
dec %rbx
mov (%rcx), %rdx
nop
nop
nop
nop
sub %rdi, %rdi
// Store
mov $0x1ea3550000000d83, %rdi
nop
nop
nop
cmp $2910, %rbx
mov $0x5152535455565758, %rdx
movq %rdx, (%rdi)
xor $34108, %rbp
// Faulty Load
lea addresses_US+0x8de3, %rcx
nop
inc %r11
movups (%rcx), %xmm4
vpextrq $0, %xmm4, %rax
lea oracles, %rcx
and $0xff, %rax
shlq $12, %rax
mov (%rcx,%rax,1), %rax
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %rax
pop %r11
ret
/*
<gen_faulty_load>
[REF]
{'src': {'NT': True, 'AVXalign': False, 'size': 32, 'congruent': 0, 'same': True, 'type': 'addresses_US'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_D'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 5, 'same': False, 'type': 'addresses_NC'}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'NT': False, 'AVXalign': False, 'size': 16, 'congruent': 0, 'same': True, 'type': 'addresses_US'}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'dst': {'NT': False, 'AVXalign': False, 'size': 4, 'congruent': 3, 'same': False, 'type': 'addresses_UC_ht'}, 'OP': 'STOR'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 3, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'STOR'}
{'src': {'NT': False, 'AVXalign': False, 'size': 32, 'congruent': 4, 'same': False, 'type': 'addresses_WT_ht'}, 'OP': 'LOAD'}
{'src': {'NT': False, 'AVXalign': False, 'size': 1, 'congruent': 11, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'LOAD'}
{'dst': {'NT': False, 'AVXalign': False, 'size': 8, 'congruent': 7, 'same': False, 'type': 'addresses_D_ht'}, 'OP': 'STOR'}
{'00': 4087}
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*/
|
// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2017-2019 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifdef HAVE_CONFIG_H
#include "config/micropaymentcoin-config.h"
#endif
#include "netbase.h"
#include "hash.h"
#include "sync.h"
#include "uint256.h"
#include "random.h"
#include "util.h"
#include "utilstrencodings.h"
#ifdef HAVE_GETADDRINFO_A
#include <netdb.h>
#endif
#ifndef WIN32
#if HAVE_INET_PTON
#include <arpa/inet.h>
#endif
#include <fcntl.h>
#endif
#include <boost/algorithm/string/case_conv.hpp> // for to_lower()
#include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith()
#include <boost/thread.hpp>
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
using namespace std;
// Settings
static proxyType proxyInfo[NET_MAX];
static proxyType nameProxy;
static CCriticalSection cs_proxyInfos;
int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT;
bool fNameLookup = false;
static const unsigned char pchIPv4[12] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff};
// Need ample time for negotiation for very slow proxies such as Tor (milliseconds)
static const int SOCKS5_RECV_TIMEOUT = 20 * 1000;
enum Network ParseNetwork(std::string net)
{
boost::to_lower(net);
if (net == "ipv4") return NET_IPV4;
if (net == "ipv6") return NET_IPV6;
if (net == "tor" || net == "onion") return NET_TOR;
return NET_UNROUTABLE;
}
std::string GetNetworkName(enum Network net)
{
switch (net) {
case NET_IPV4:
return "ipv4";
case NET_IPV6:
return "ipv6";
case NET_TOR:
return "onion";
default:
return "";
}
}
void SplitHostPort(std::string in, int& portOut, std::string& hostOut)
{
size_t colon = in.find_last_of(':');
// if a : is found, and it either follows a [...], or no other : is in the string, treat it as port separator
bool fHaveColon = colon != in.npos;
bool fBracketed = fHaveColon && (in[0] == '[' && in[colon - 1] == ']'); // if there is a colon, and in[0]=='[', colon is not 0, so in[colon-1] is safe
bool fMultiColon = fHaveColon && (in.find_last_of(':', colon - 1) != in.npos);
if (fHaveColon && (colon == 0 || fBracketed || !fMultiColon)) {
int32_t n;
if (ParseInt32(in.substr(colon + 1), &n) && n > 0 && n < 0x10000) {
in = in.substr(0, colon);
portOut = n;
}
}
if (in.size() > 0 && in[0] == '[' && in[in.size() - 1] == ']')
hostOut = in.substr(1, in.size() - 2);
else
hostOut = in;
}
bool static LookupIntern(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
vIP.clear();
{
CNetAddr addr;
if (addr.SetSpecial(std::string(pszName))) {
vIP.push_back(addr);
return true;
}
}
#ifdef HAVE_GETADDRINFO_A
struct in_addr ipv4_addr;
#ifdef HAVE_INET_PTON
if (inet_pton(AF_INET, pszName, &ipv4_addr) > 0) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
struct in6_addr ipv6_addr;
if (inet_pton(AF_INET6, pszName, &ipv6_addr) > 0) {
vIP.push_back(CNetAddr(ipv6_addr));
return true;
}
#else
ipv4_addr.s_addr = inet_addr(pszName);
if (ipv4_addr.s_addr != INADDR_NONE) {
vIP.push_back(CNetAddr(ipv4_addr));
return true;
}
#endif
#endif
struct addrinfo aiHint;
memset(&aiHint, 0, sizeof(struct addrinfo));
aiHint.ai_socktype = SOCK_STREAM;
aiHint.ai_protocol = IPPROTO_TCP;
aiHint.ai_family = AF_UNSPEC;
#ifdef WIN32
aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST;
#else
aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST;
#endif
struct addrinfo* aiRes = NULL;
#ifdef HAVE_GETADDRINFO_A
struct gaicb gcb, *query = &gcb;
memset(query, 0, sizeof(struct gaicb));
gcb.ar_name = pszName;
gcb.ar_request = &aiHint;
int nErr = getaddrinfo_a(GAI_NOWAIT, &query, 1, NULL);
if (nErr)
return false;
do {
// Should set the timeout limit to a resonable value to avoid
// generating unnecessary checking call during the polling loop,
// while it can still response to stop request quick enough.
// 2 seconds looks fine in our situation.
struct timespec ts = {2, 0};
gai_suspend(&query, 1, &ts);
boost::this_thread::interruption_point();
nErr = gai_error(query);
if (0 == nErr)
aiRes = query->ar_result;
} while (nErr == EAI_INPROGRESS);
#else
int nErr = getaddrinfo(pszName, NULL, &aiHint, &aiRes);
#endif
if (nErr)
return false;
struct addrinfo* aiTrav = aiRes;
while (aiTrav != NULL && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) {
if (aiTrav->ai_family == AF_INET) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in));
vIP.push_back(CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr));
}
if (aiTrav->ai_family == AF_INET6) {
assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6));
vIP.push_back(CNetAddr(((struct sockaddr_in6*)(aiTrav->ai_addr))->sin6_addr));
}
aiTrav = aiTrav->ai_next;
}
freeaddrinfo(aiRes);
return (vIP.size() > 0);
}
bool LookupHost(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup)
{
std::string strHost(pszName);
if (strHost.empty())
return false;
if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) {
strHost = strHost.substr(1, strHost.size() - 2);
}
return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup);
}
bool Lookup(const char* pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions)
{
if (pszName[0] == 0)
return false;
int port = portDefault;
std::string hostname = "";
SplitHostPort(std::string(pszName), port, hostname);
std::vector<CNetAddr> vIP;
bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup);
if (!fRet)
return false;
vAddr.resize(vIP.size());
for (unsigned int i = 0; i < vIP.size(); i++)
vAddr[i] = CService(vIP[i], port);
return true;
}
bool Lookup(const char* pszName, CService& addr, int portDefault, bool fAllowLookup)
{
std::vector<CService> vService;
bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1);
if (!fRet)
return false;
addr = vService[0];
return true;
}
bool LookupNumeric(const char* pszName, CService& addr, int portDefault)
{
return Lookup(pszName, addr, portDefault, false);
}
struct timeval MillisToTimeval(int64_t nTimeout)
{
struct timeval timeout;
timeout.tv_sec = nTimeout / 1000;
timeout.tv_usec = (nTimeout % 1000) * 1000;
return timeout;
}
/**
* Read bytes from socket. This will either read the full number of bytes requested
* or return False on error or timeout.
* This function can be interrupted by boost thread interrupt.
*
* @param data Buffer to receive into
* @param len Length of data to receive
* @param timeout Timeout in milliseconds for receive operation
*
* @note This function requires that hSocket is in non-blocking mode.
*/
bool static InterruptibleRecv(char* data, size_t len, int timeout, SOCKET& hSocket)
{
int64_t curTime = GetTimeMillis();
int64_t endTime = curTime + timeout;
// Maximum time to wait in one select call. It will take up until this time (in millis)
// to break off in case of an interruption.
const int64_t maxWait = 1000;
while (len > 0 && curTime < endTime) {
ssize_t ret = recv(hSocket, data, len, 0); // Optimistically try the recv first
if (ret > 0) {
len -= ret;
data += ret;
} else if (ret == 0) { // Unexpected disconnection
return false;
} else { // Other error or blocking
int nErr = WSAGetLastError();
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
if (!IsSelectableSocket(hSocket)) {
return false;
}
struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait));
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, &fdset, NULL, NULL, &tval);
if (nRet == SOCKET_ERROR) {
return false;
}
} else {
return false;
}
}
boost::this_thread::interruption_point();
curTime = GetTimeMillis();
}
return len == 0;
}
struct ProxyCredentials
{
std::string username;
std::string password;
};
/** Connect using SOCKS5 (as described in RFC1928) */
bool static Socks5(string strDest, int port, const ProxyCredentials *auth, SOCKET& hSocket)
{
LogPrintf("SOCKS5 connecting %s\n", strDest);
if (strDest.size() > 255) {
CloseSocket(hSocket);
return error("Hostname too long");
}
// Accepted authentication methods
std::vector<uint8_t> vSocks5Init;
vSocks5Init.push_back(0x05);
if (auth) {
vSocks5Init.push_back(0x02); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
vSocks5Init.push_back(0x02); // X'02' USERNAME/PASSWORD (RFC1929)
} else {
vSocks5Init.push_back(0x01); // # METHODS
vSocks5Init.push_back(0x00); // X'00' NO AUTHENTICATION REQUIRED
}
ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5Init.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet1[2];
if (!InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet1[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to initialize");
}
if (pchRet1[1] == 0x02 && auth) {
// Perform username/password authentication (as described in RFC1929)
std::vector<uint8_t> vAuth;
vAuth.push_back(0x01);
if (auth->username.size() > 255 || auth->password.size() > 255)
return error("Proxy username or password too long");
vAuth.push_back(auth->username.size());
vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end());
vAuth.push_back(auth->password.size());
vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end());
ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vAuth.size()) {
CloseSocket(hSocket);
return error("Error sending authentication to proxy");
}
LogPrint("proxy", "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password);
char pchRetA[2];
if (!InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy authentication response");
}
if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) {
CloseSocket(hSocket);
return error("Proxy authentication unsuccesful");
}
} else if (pchRet1[1] == 0x00) {
// Perform no authentication
} else {
CloseSocket(hSocket);
return error("Proxy requested wrong authentication method %02x", pchRet1[1]);
}
std::vector<uint8_t> vSocks5;
vSocks5.push_back(0x05); // VER protocol version
vSocks5.push_back(0x01); // CMD CONNECT
vSocks5.push_back(0x00); // RSV Reserved
vSocks5.push_back(0x03); // ATYP DOMAINNAME
vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function
vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end());
vSocks5.push_back((port >> 8) & 0xFF);
vSocks5.push_back((port >> 0) & 0xFF);
ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL);
if (ret != (ssize_t)vSocks5.size()) {
CloseSocket(hSocket);
return error("Error sending to proxy");
}
char pchRet2[4];
if (!InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading proxy response");
}
if (pchRet2[0] != 0x05) {
CloseSocket(hSocket);
return error("Proxy failed to accept request");
}
if (pchRet2[1] != 0x00) {
CloseSocket(hSocket);
switch (pchRet2[1]) {
case 0x01:
return error("Proxy error: general failure");
case 0x02:
return error("Proxy error: connection not allowed");
case 0x03:
return error("Proxy error: network unreachable");
case 0x04:
return error("Proxy error: host unreachable");
case 0x05:
return error("Proxy error: connection refused");
case 0x06:
return error("Proxy error: TTL expired");
case 0x07:
return error("Proxy error: protocol error");
case 0x08:
return error("Proxy error: address type not supported");
default:
return error("Proxy error: unknown");
}
}
if (pchRet2[2] != 0x00) {
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
char pchRet3[256];
switch (pchRet2[3]) {
case 0x01:
ret = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x04:
ret = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket);
break;
case 0x03: {
ret = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket);
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
int nRecv = pchRet3[0];
ret = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket);
break;
}
default:
CloseSocket(hSocket);
return error("Error: malformed proxy response");
}
if (!ret) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
if (!InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) {
CloseSocket(hSocket);
return error("Error reading from proxy");
}
LogPrintf("SOCKS5 connected %s\n", strDest);
return true;
}
bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout)
{
hSocketRet = INVALID_SOCKET;
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString());
return false;
}
SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hSocket == INVALID_SOCKET)
return false;
#ifdef SO_NOSIGPIPE
int set = 1;
// Different way of disabling SIGPIPE on BSD
setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int));
#endif
// Set to non-blocking
if (!SetSocketNonBlocking(hSocket, true))
return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
// WSAEINVAL is here because some legacy version of winsock uses it
if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) {
struct timeval timeout = MillisToTimeval(nTimeout);
fd_set fdset;
FD_ZERO(&fdset);
FD_SET(hSocket, &fdset);
int nRet = select(hSocket + 1, NULL, &fdset, NULL, &timeout);
if (nRet == 0) {
LogPrint("net", "connection to %s timeout\n", addrConnect.ToString());
CloseSocket(hSocket);
return false;
}
if (nRet == SOCKET_ERROR) {
LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
socklen_t nRetSize = sizeof(nRet);
#ifdef WIN32
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR)
#else
if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR)
#endif
{
LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
if (nRet != 0) {
LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet));
CloseSocket(hSocket);
return false;
}
}
#ifdef WIN32
else if (WSAGetLastError() != WSAEISCONN)
#else
else
#endif
{
LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError()));
CloseSocket(hSocket);
return false;
}
}
hSocketRet = hSocket;
return true;
}
bool SetProxy(enum Network net, const proxyType &addrProxy)
{
assert(net >= 0 && net < NET_MAX);
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
proxyInfo[net] = addrProxy;
return true;
}
bool GetProxy(enum Network net, proxyType& proxyInfoOut)
{
assert(net >= 0 && net < NET_MAX);
LOCK(cs_proxyInfos);
if (!proxyInfo[net].IsValid())
return false;
proxyInfoOut = proxyInfo[net];
return true;
}
bool SetNameProxy(const proxyType &addrProxy)
{
if (!addrProxy.IsValid())
return false;
LOCK(cs_proxyInfos);
nameProxy = addrProxy;
return true;
}
bool GetNameProxy(proxyType &nameProxyOut)
{
LOCK(cs_proxyInfos);
if (!nameProxy.IsValid())
return false;
nameProxyOut = nameProxy;
return true;
}
bool HaveNameProxy()
{
LOCK(cs_proxyInfos);
return nameProxy.IsValid();
}
bool IsProxy(const CNetAddr& addr)
{
LOCK(cs_proxyInfos);
for (int i = 0; i < NET_MAX; i++) {
if (addr == (CNetAddr)proxyInfo[i].proxy)
return true;
}
return false;
}
static bool ConnectThroughProxy(const proxyType &proxy, const std::string strDest, int port, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
SOCKET hSocket = INVALID_SOCKET;
// first connect to proxy server
if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) {
if (outProxyConnectionFailed)
*outProxyConnectionFailed = true;
return false;
}
// do socks negotiation
if (proxy.randomize_credentials) {
ProxyCredentials random_auth;
random_auth.username = strprintf("%i", insecure_rand());
random_auth.password = strprintf("%i", insecure_rand());
if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket))
return false;
} else {
if (!Socks5(strDest, (unsigned short)port, 0, hSocket))
return false;
}
hSocketRet = hSocket;
return true;
}
bool ConnectSocket(const CService &addrDest, SOCKET& hSocketRet, int nTimeout, bool *outProxyConnectionFailed)
{
proxyType proxy;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
if (GetProxy(addrDest.GetNetwork(), proxy))
return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed);
else // no proxy needed (none set for target network)
return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout);
}
bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed)
{
string strDest;
int port = portDefault;
if (outProxyConnectionFailed)
*outProxyConnectionFailed = false;
SplitHostPort(string(pszDest), port, strDest);
proxyType nameProxy;
GetNameProxy(nameProxy);
CService addrResolved(CNetAddr(strDest, fNameLookup && !HaveNameProxy()), port);
if (addrResolved.IsValid()) {
addr = addrResolved;
return ConnectSocket(addr, hSocketRet, nTimeout);
}
addr = CService("0.0.0.0:0");
if (!HaveNameProxy())
return false;
return ConnectThroughProxy(nameProxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed);
}
void CNetAddr::Init()
{
memset(ip, 0, sizeof(ip));
}
void CNetAddr::SetIP(const CNetAddr& ipIn)
{
memcpy(ip, ipIn.ip, sizeof(ip));
}
void CNetAddr::SetRaw(Network network, const uint8_t* ip_in)
{
switch (network) {
case NET_IPV4:
memcpy(ip, pchIPv4, 12);
memcpy(ip + 12, ip_in, 4);
break;
case NET_IPV6:
memcpy(ip, ip_in, 16);
break;
default:
assert(!"invalid network");
}
}
static const unsigned char pchOnionCat[] = {0xFD, 0x87, 0xD8, 0x7E, 0xEB, 0x43};
bool CNetAddr::SetSpecial(const std::string& strName)
{
if (strName.size() > 6 && strName.substr(strName.size() - 6, 6) == ".onion") {
std::vector<unsigned char> vchAddr = DecodeBase32(strName.substr(0, strName.size() - 6).c_str());
if (vchAddr.size() != 16 - sizeof(pchOnionCat))
return false;
memcpy(ip, pchOnionCat, sizeof(pchOnionCat));
for (unsigned int i = 0; i < 16 - sizeof(pchOnionCat); i++)
ip[i + sizeof(pchOnionCat)] = vchAddr[i];
return true;
}
return false;
}
CNetAddr::CNetAddr()
{
Init();
}
CNetAddr::CNetAddr(const struct in_addr& ipv4Addr)
{
SetRaw(NET_IPV4, (const uint8_t*)&ipv4Addr);
}
CNetAddr::CNetAddr(const struct in6_addr& ipv6Addr)
{
SetRaw(NET_IPV6, (const uint8_t*)&ipv6Addr);
}
CNetAddr::CNetAddr(const char* pszIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(pszIp, vIP, 1, fAllowLookup))
*this = vIP[0];
}
CNetAddr::CNetAddr(const std::string& strIp, bool fAllowLookup)
{
Init();
std::vector<CNetAddr> vIP;
if (LookupHost(strIp.c_str(), vIP, 1, fAllowLookup))
*this = vIP[0];
}
unsigned int CNetAddr::GetByte(int n) const
{
return ip[15 - n];
}
bool CNetAddr::IsIPv4() const
{
return (memcmp(ip, pchIPv4, sizeof(pchIPv4)) == 0);
}
bool CNetAddr::IsIPv6() const
{
return (!IsIPv4() && !IsTor());
}
bool CNetAddr::IsRFC1918() const
{
return IsIPv4() && (GetByte(3) == 10 ||
(GetByte(3) == 192 && GetByte(2) == 168) ||
(GetByte(3) == 172 && (GetByte(2) >= 16 && GetByte(2) <= 31)));
}
bool CNetAddr::IsRFC2544() const
{
return IsIPv4() && GetByte(3) == 198 && (GetByte(2) == 18 || GetByte(2) == 19);
}
bool CNetAddr::IsRFC3927() const
{
return IsIPv4() && (GetByte(3) == 169 && GetByte(2) == 254);
}
bool CNetAddr::IsRFC6598() const
{
return IsIPv4() && GetByte(3) == 100 && GetByte(2) >= 64 && GetByte(2) <= 127;
}
bool CNetAddr::IsRFC5737() const
{
return IsIPv4() && ((GetByte(3) == 192 && GetByte(2) == 0 && GetByte(1) == 2) ||
(GetByte(3) == 198 && GetByte(2) == 51 && GetByte(1) == 100) ||
(GetByte(3) == 203 && GetByte(2) == 0 && GetByte(1) == 113));
}
bool CNetAddr::IsRFC3849() const
{
return GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x0D && GetByte(12) == 0xB8;
}
bool CNetAddr::IsRFC3964() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x02);
}
bool CNetAddr::IsRFC6052() const
{
static const unsigned char pchRFC6052[] = {0, 0x64, 0xFF, 0x9B, 0, 0, 0, 0, 0, 0, 0, 0};
return (memcmp(ip, pchRFC6052, sizeof(pchRFC6052)) == 0);
}
bool CNetAddr::IsRFC4380() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0 && GetByte(12) == 0);
}
bool CNetAddr::IsRFC4862() const
{
static const unsigned char pchRFC4862[] = {0xFE, 0x80, 0, 0, 0, 0, 0, 0};
return (memcmp(ip, pchRFC4862, sizeof(pchRFC4862)) == 0);
}
bool CNetAddr::IsRFC4193() const
{
return ((GetByte(15) & 0xFE) == 0xFC);
}
bool CNetAddr::IsRFC6145() const
{
static const unsigned char pchRFC6145[] = {0, 0, 0, 0, 0, 0, 0, 0, 0xFF, 0xFF, 0, 0};
return (memcmp(ip, pchRFC6145, sizeof(pchRFC6145)) == 0);
}
bool CNetAddr::IsRFC4843() const
{
return (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x00 && (GetByte(12) & 0xF0) == 0x10);
}
bool CNetAddr::IsTor() const
{
return (memcmp(ip, pchOnionCat, sizeof(pchOnionCat)) == 0);
}
bool CNetAddr::IsLocal() const
{
// IPv4 loopback
if (IsIPv4() && (GetByte(3) == 127 || GetByte(3) == 0))
return true;
// IPv6 loopback (::1/128)
static const unsigned char pchLocal[16] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1};
if (memcmp(ip, pchLocal, 16) == 0)
return true;
return false;
}
bool CNetAddr::IsMulticast() const
{
return (IsIPv4() && (GetByte(3) & 0xF0) == 0xE0) || (GetByte(15) == 0xFF);
}
bool CNetAddr::IsValid() const
{
// Cleanup 3-byte shifted addresses caused by garbage in size field
// of addr messages from versions before 0.2.9 checksum.
// Two consecutive addr messages look like this:
// header20 vectorlen3 addr26 addr26 addr26 header20 vectorlen3 addr26 addr26 addr26...
// so if the first length field is garbled, it reads the second batch
// of addr misaligned by 3 bytes.
if (memcmp(ip, pchIPv4 + 3, sizeof(pchIPv4) - 3) == 0)
return false;
// unspecified IPv6 address (::/128)
unsigned char ipNone[16] = {};
if (memcmp(ip, ipNone, 16) == 0)
return false;
// documentation IPv6 address
if (IsRFC3849())
return false;
if (IsIPv4()) {
// INADDR_NONE
uint32_t ipNone = INADDR_NONE;
if (memcmp(ip + 12, &ipNone, 4) == 0)
return false;
// 0
ipNone = 0;
if (memcmp(ip + 12, &ipNone, 4) == 0)
return false;
}
return true;
}
bool CNetAddr::IsRoutable() const
{
return IsValid() && !(IsRFC1918() || IsRFC2544() || IsRFC3927() || IsRFC4862() || IsRFC6598() || IsRFC5737() || (IsRFC4193() && !IsTor()) || IsRFC4843() || IsLocal());
}
enum Network CNetAddr::GetNetwork() const
{
if (!IsRoutable())
return NET_UNROUTABLE;
if (IsIPv4())
return NET_IPV4;
if (IsTor())
return NET_TOR;
return NET_IPV6;
}
std::string CNetAddr::ToStringIP() const
{
if (IsTor())
return EncodeBase32(&ip[6], 10) + ".onion";
CService serv(*this, 0);
struct sockaddr_storage sockaddr;
socklen_t socklen = sizeof(sockaddr);
if (serv.GetSockAddr((struct sockaddr*)&sockaddr, &socklen)) {
char name[1025] = "";
if (!getnameinfo((const struct sockaddr*)&sockaddr, socklen, name, sizeof(name), NULL, 0, NI_NUMERICHOST))
return std::string(name);
}
if (IsIPv4())
return strprintf("%u.%u.%u.%u", GetByte(3), GetByte(2), GetByte(1), GetByte(0));
else
return strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
GetByte(15) << 8 | GetByte(14), GetByte(13) << 8 | GetByte(12),
GetByte(11) << 8 | GetByte(10), GetByte(9) << 8 | GetByte(8),
GetByte(7) << 8 | GetByte(6), GetByte(5) << 8 | GetByte(4),
GetByte(3) << 8 | GetByte(2), GetByte(1) << 8 | GetByte(0));
}
std::string CNetAddr::ToString() const
{
return ToStringIP();
}
bool operator==(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) == 0);
}
bool operator!=(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) != 0);
}
bool operator<(const CNetAddr& a, const CNetAddr& b)
{
return (memcmp(a.ip, b.ip, 16) < 0);
}
bool CNetAddr::GetInAddr(struct in_addr* pipv4Addr) const
{
if (!IsIPv4())
return false;
memcpy(pipv4Addr, ip + 12, 4);
return true;
}
bool CNetAddr::GetIn6Addr(struct in6_addr* pipv6Addr) const
{
memcpy(pipv6Addr, ip, 16);
return true;
}
// get canonical identifier of an address' group
// no two connections will be attempted to addresses with the same group
std::vector<unsigned char> CNetAddr::GetGroup() const
{
std::vector<unsigned char> vchRet;
int nClass = NET_IPV6;
int nStartByte = 0;
int nBits = 16;
// all local addresses belong to the same group
if (IsLocal()) {
nClass = 255;
nBits = 0;
}
// all unroutable addresses belong to the same group
if (!IsRoutable()) {
nClass = NET_UNROUTABLE;
nBits = 0;
}
// for IPv4 addresses, '1' + the 16 higher-order bits of the IP
// includes mapped IPv4, SIIT translated IPv4, and the well-known prefix
else if (IsIPv4() || IsRFC6145() || IsRFC6052()) {
nClass = NET_IPV4;
nStartByte = 12;
}
// for 6to4 tunnelled addresses, use the encapsulated IPv4 address
else if (IsRFC3964()) {
nClass = NET_IPV4;
nStartByte = 2;
}
// for Teredo-tunnelled IPv6 addresses, use the encapsulated IPv4 address
else if (IsRFC4380()) {
vchRet.push_back(NET_IPV4);
vchRet.push_back(GetByte(3) ^ 0xFF);
vchRet.push_back(GetByte(2) ^ 0xFF);
return vchRet;
} else if (IsTor()) {
nClass = NET_TOR;
nStartByte = 6;
nBits = 4;
}
// for he.net, use /36 groups
else if (GetByte(15) == 0x20 && GetByte(14) == 0x01 && GetByte(13) == 0x04 && GetByte(12) == 0x70)
nBits = 36;
// for the rest of the IPv6 network, use /32 groups
else
nBits = 32;
vchRet.push_back(nClass);
while (nBits >= 8) {
vchRet.push_back(GetByte(15 - nStartByte));
nStartByte++;
nBits -= 8;
}
if (nBits > 0)
vchRet.push_back(GetByte(15 - nStartByte) | ((1 << nBits) - 1));
return vchRet;
}
uint64_t CNetAddr::GetHash() const
{
uint256 hash = Hash(&ip[0], &ip[16]);
uint64_t nRet;
memcpy(&nRet, &hash, sizeof(nRet));
return nRet;
}
// private extensions to enum Network, only returned by GetExtNetwork,
// and only used in GetReachabilityFrom
static const int NET_UNKNOWN = NET_MAX + 0;
static const int NET_TEREDO = NET_MAX + 1;
int static GetExtNetwork(const CNetAddr* addr)
{
if (addr == NULL)
return NET_UNKNOWN;
if (addr->IsRFC4380())
return NET_TEREDO;
return addr->GetNetwork();
}
/** Calculates a metric for how reachable (*this) is from a given partner */
int CNetAddr::GetReachabilityFrom(const CNetAddr* paddrPartner) const
{
enum Reachability {
REACH_UNREACHABLE,
REACH_DEFAULT,
REACH_TEREDO,
REACH_IPV6_WEAK,
REACH_IPV4,
REACH_IPV6_STRONG,
REACH_PRIVATE
};
if (!IsRoutable())
return REACH_UNREACHABLE;
int ourNet = GetExtNetwork(this);
int theirNet = GetExtNetwork(paddrPartner);
bool fTunnel = IsRFC3964() || IsRFC6052() || IsRFC6145();
switch (theirNet) {
case NET_IPV4:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_IPV4:
return REACH_IPV4;
}
case NET_IPV6:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV4:
return REACH_IPV4;
case NET_IPV6:
return fTunnel ? REACH_IPV6_WEAK : REACH_IPV6_STRONG; // only prefer giving our IPv6 address if it's not tunnelled
}
case NET_TOR:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_IPV4:
return REACH_IPV4; // Tor users can connect to IPv4 as well
case NET_TOR:
return REACH_PRIVATE;
}
case NET_TEREDO:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV6:
return REACH_IPV6_WEAK;
case NET_IPV4:
return REACH_IPV4;
}
case NET_UNKNOWN:
case NET_UNROUTABLE:
default:
switch (ourNet) {
default:
return REACH_DEFAULT;
case NET_TEREDO:
return REACH_TEREDO;
case NET_IPV6:
return REACH_IPV6_WEAK;
case NET_IPV4:
return REACH_IPV4;
case NET_TOR:
return REACH_PRIVATE; // either from Tor, or don't care about our address
}
}
}
void CService::Init()
{
port = 0;
}
CService::CService()
{
Init();
}
CService::CService(const CNetAddr& cip, unsigned short portIn) : CNetAddr(cip), port(portIn)
{
}
CService::CService(const struct in_addr& ipv4Addr, unsigned short portIn) : CNetAddr(ipv4Addr), port(portIn)
{
}
CService::CService(const struct in6_addr& ipv6Addr, unsigned short portIn) : CNetAddr(ipv6Addr), port(portIn)
{
}
CService::CService(const struct sockaddr_in& addr) : CNetAddr(addr.sin_addr), port(ntohs(addr.sin_port))
{
assert(addr.sin_family == AF_INET);
}
CService::CService(const struct sockaddr_in6& addr) : CNetAddr(addr.sin6_addr), port(ntohs(addr.sin6_port))
{
assert(addr.sin6_family == AF_INET6);
}
bool CService::SetSockAddr(const struct sockaddr* paddr)
{
switch (paddr->sa_family) {
case AF_INET:
*this = CService(*(const struct sockaddr_in*)paddr);
return true;
case AF_INET6:
*this = CService(*(const struct sockaddr_in6*)paddr);
return true;
default:
return false;
}
}
CService::CService(const char* pszIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const char* pszIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(pszIpPort, ip, portDefault, fAllowLookup))
*this = ip;
}
CService::CService(const std::string& strIpPort, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, 0, fAllowLookup))
*this = ip;
}
CService::CService(const std::string& strIpPort, int portDefault, bool fAllowLookup)
{
Init();
CService ip;
if (Lookup(strIpPort.c_str(), ip, portDefault, fAllowLookup))
*this = ip;
}
unsigned short CService::GetPort() const
{
return port;
}
bool operator==(const CService& a, const CService& b)
{
return (CNetAddr)a == (CNetAddr)b && a.port == b.port;
}
bool operator!=(const CService& a, const CService& b)
{
return (CNetAddr)a != (CNetAddr)b || a.port != b.port;
}
bool operator<(const CService& a, const CService& b)
{
return (CNetAddr)a < (CNetAddr)b || ((CNetAddr)a == (CNetAddr)b && a.port < b.port);
}
bool CService::GetSockAddr(struct sockaddr* paddr, socklen_t* addrlen) const
{
if (IsIPv4()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in))
return false;
*addrlen = sizeof(struct sockaddr_in);
struct sockaddr_in* paddrin = (struct sockaddr_in*)paddr;
memset(paddrin, 0, *addrlen);
if (!GetInAddr(&paddrin->sin_addr))
return false;
paddrin->sin_family = AF_INET;
paddrin->sin_port = htons(port);
return true;
}
if (IsIPv6()) {
if (*addrlen < (socklen_t)sizeof(struct sockaddr_in6))
return false;
*addrlen = sizeof(struct sockaddr_in6);
struct sockaddr_in6* paddrin6 = (struct sockaddr_in6*)paddr;
memset(paddrin6, 0, *addrlen);
if (!GetIn6Addr(&paddrin6->sin6_addr))
return false;
paddrin6->sin6_family = AF_INET6;
paddrin6->sin6_port = htons(port);
return true;
}
return false;
}
std::vector<unsigned char> CService::GetKey() const
{
std::vector<unsigned char> vKey;
vKey.resize(18);
memcpy(&vKey[0], ip, 16);
vKey[16] = port / 0x100;
vKey[17] = port & 0x0FF;
return vKey;
}
std::string CService::ToStringPort() const
{
return strprintf("%u", port);
}
std::string CService::ToStringIPPort() const
{
if (IsIPv4() || IsTor()) {
return ToStringIP() + ":" + ToStringPort();
} else {
return "[" + ToStringIP() + "]:" + ToStringPort();
}
}
std::string CService::ToString() const
{
return ToStringIPPort();
}
void CService::SetPort(unsigned short portIn)
{
port = portIn;
}
CSubNet::CSubNet() : valid(false)
{
memset(netmask, 0, sizeof(netmask));
}
CSubNet::CSubNet(const std::string& strSubnet, bool fAllowLookup)
{
size_t slash = strSubnet.find_last_of('/');
std::vector<CNetAddr> vIP;
valid = true;
// Default to /32 (IPv4) or /128 (IPv6), i.e. match single address
memset(netmask, 255, sizeof(netmask));
std::string strAddress = strSubnet.substr(0, slash);
if (LookupHost(strAddress.c_str(), vIP, 1, fAllowLookup)) {
network = vIP[0];
if (slash != strSubnet.npos) {
std::string strNetmask = strSubnet.substr(slash + 1);
int32_t n;
// IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n
const int astartofs = network.IsIPv4() ? 12 : 0;
if (ParseInt32(strNetmask, &n)) // If valid number, assume /24 symtex
{
if (n >= 0 && n <= (128 - astartofs * 8)) // Only valid if in range of bits of address
{
n += astartofs * 8;
// Clear bits [n..127]
for (; n < 128; ++n)
netmask[n >> 3] &= ~(1 << (7 - (n & 7)));
} else {
valid = false;
}
} else // If not a valid number, try full netmask syntax
{
if (LookupHost(strNetmask.c_str(), vIP, 1, false)) // Never allow lookup for netmask
{
// Copy only the *last* four bytes in case of IPv4, the rest of the mask should stay 1's as
// we don't want pchIPv4 to be part of the mask.
for (int x = astartofs; x < 16; ++x)
netmask[x] = vIP[0].ip[x];
} else {
valid = false;
}
}
}
} else {
valid = false;
}
// Normalize network according to netmask
for (int x = 0; x < 16; ++x)
network.ip[x] &= netmask[x];
}
CSubNet::CSubNet(const CNetAddr &addr):
valid(addr.IsValid())
{
memset(netmask, 255, sizeof(netmask));
network = addr;
}
bool CSubNet::Match(const CNetAddr& addr) const
{
if (!valid || !addr.IsValid())
return false;
for (int x = 0; x < 16; ++x)
if ((addr.ip[x] & netmask[x]) != network.ip[x])
return false;
return true;
}
static inline int NetmaskBits(uint8_t x)
{
switch(x) {
case 0x00: return 0; break;
case 0x80: return 1; break;
case 0xc0: return 2; break;
case 0xe0: return 3; break;
case 0xf0: return 4; break;
case 0xf8: return 5; break;
case 0xfc: return 6; break;
case 0xfe: return 7; break;
case 0xff: return 8; break;
default: return -1; break;
}
}
std::string CSubNet::ToString() const
{
/* Parse binary 1{n}0{N-n} to see if mask can be represented as /n */
int cidr = 0;
bool valid_cidr = true;
int n = network.IsIPv4() ? 12 : 0;
for (; n < 16 && netmask[n] == 0xff; ++n)
cidr += 8;
if (n < 16) {
int bits = NetmaskBits(netmask[n]);
if (bits < 0)
valid_cidr = false;
else
cidr += bits;
++n;
}
for (; n < 16 && valid_cidr; ++n)
if (netmask[n] != 0x00)
valid_cidr = false;
/* Format output */
std::string strNetmask;
if (valid_cidr) {
strNetmask = strprintf("%u", cidr);
} else {
if (network.IsIPv4())
strNetmask = strprintf("%u.%u.%u.%u", netmask[12], netmask[13], netmask[14], netmask[15]);
else
strNetmask = strprintf("%x:%x:%x:%x:%x:%x:%x:%x",
netmask[0] << 8 | netmask[1], netmask[2] << 8 | netmask[3],
netmask[4] << 8 | netmask[5], netmask[6] << 8 | netmask[7],
netmask[8] << 8 | netmask[9], netmask[10] << 8 | netmask[11],
netmask[12] << 8 | netmask[13], netmask[14] << 8 | netmask[15]);
}
return network.ToString() + "/" + strNetmask;
}
bool CSubNet::IsValid() const
{
return valid;
}
bool operator==(const CSubNet& a, const CSubNet& b)
{
return a.valid == b.valid && a.network == b.network && !memcmp(a.netmask, b.netmask, 16);
}
bool operator!=(const CSubNet& a, const CSubNet& b)
{
return !(a == b);
}
bool operator<(const CSubNet& a, const CSubNet& b)
{
return (a.network < b.network || (a.network == b.network && memcmp(a.netmask, b.netmask, 16) < 0));
}
#ifdef WIN32
std::string NetworkErrorString(int err)
{
char buf[256];
buf[0] = 0;
if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK,
NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf, sizeof(buf), NULL)) {
return strprintf("%s (%d)", buf, err);
} else {
return strprintf("Unknown error (%d)", err);
}
}
#else
std::string NetworkErrorString(int err)
{
char buf[256];
const char* s = buf;
buf[0] = 0;
/* Too bad there are two incompatible implementations of the
* thread-safe strerror. */
#ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */
s = strerror_r(err, buf, sizeof(buf));
#else /* POSIX variant always returns message in buffer */
if (strerror_r(err, buf, sizeof(buf)))
buf[0] = 0;
#endif
return strprintf("%s (%d)", s, err);
}
#endif
bool CloseSocket(SOCKET& hSocket)
{
if (hSocket == INVALID_SOCKET)
return false;
#ifdef WIN32
int ret = closesocket(hSocket);
#else
int ret = close(hSocket);
#endif
hSocket = INVALID_SOCKET;
return ret != SOCKET_ERROR;
}
bool SetSocketNonBlocking(SOCKET& hSocket, bool fNonBlocking)
{
if (fNonBlocking) {
#ifdef WIN32
u_long nOne = 1;
if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
} else {
#ifdef WIN32
u_long nZero = 0;
if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) {
#else
int fFlags = fcntl(hSocket, F_GETFL, 0);
if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) {
#endif
CloseSocket(hSocket);
return false;
}
}
return true;
}
|
;
; Startup for the CCE MC-1000
;
; Stefano Bodrato - Feb. 2013
;
; $Id: mc1000_crt0.asm,v 1.22 2016/07/15 21:03:25 dom Exp $
;
; There are a couple of #pragma optimization directives
; this file:
;
; #pragma output nostreams - No stdio disc files
; #pragma output nogfx - Saves memory in TEXT only programs
MODULE mc1000_crt0
;--------
; Include zcc_opt.def to find out some info
;--------
defc crt0 = 1
INCLUDE "zcc_opt.def"
;--------
; Some scope definitions
;--------
EXTERN _main ;main() is always external to crt0 code
PUBLIC cleanup ;jp'd to by exit()
PUBLIC l_dcal ;jp(hl)
PUBLIC pixeladdress
PUBLIC clg
PUBLIC pix_return
PUBLIC pix_rl
PUBLIC pix_pre
PUBLIC pix_post
PUBLIC gfxbyte_get
PUBLIC ansi_cls
PUBLIC ansi_del_line
PUBLIC ansi_SCROLLUP
PUBLIC FRAMES
IF !DEFINED_CRT_ORG_CODE
IF (startup=2)
defc CRT_ORG_CODE = $100 ; Direct M/C mode, including system variables on top 100h bytes
ELSE
defc CRT_ORG_CODE = 981 ; BASIC startup mode (correct location TBD)
ENDIF
ENDIF
; Now, getting to the real stuff now!
org CRT_ORG_CODE
IF (startup=2)
; native M/C startup mode
; "TLOAD" mode
;
defb $ff,$ff,$ff
MC_PGM:
MC_PGN:
MC_MUSIC:
defb $ff
MC_PLAY:
defb $01
MC_PLAYMX:
defb $01
MC_HEAD:
defb $00
MC_RANDOM:
defw $ffff
MC_RCRDPT:
defw MC_RECORD
MC_RECORD:
defb $00,$00
defb $00,$00
defb $00,$00
defb $00,$00
defb $00,$00
defb $00,$00
defb $00,$00
defb $00,$00
MC_KEY0:
defb $ff,$ff,$ff,$ff
;
defb $ff
MC_JOB:
ret
defb $ff,$ff
MC_SCOREA:
defb $00
MC_SCOREB:
defb $00
MC_SHAPE0:
defb $ff
;
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff
MC_JOBM:
ret
defb $ff,$ff
;
defb $ff,$ff
MC_TABLE:
MC_NSA:
defw $ffff
MC_NAA:
defw $ffff
MC_AVALUE:
defb $00
VOICEA:
defb $ff
MC_INTRPA:
defb $ff
MC_TEMPA:
defb $ff
MC_INTA:
defb $ff
MC_NSB:
defw $ffff
MC_NBB:
defw $ffff
MC_BVALUE:
defb $00
MC_VOICEB:
defb $ff
MC_INTRPB:
defb $ff
MC_TEMPB:
defb $ff
MC_INTB:
defb $ff
MC_NSC:
defw $ffff
MC_NCC:
defw $ffff
MC_CVALUE:
defb $00
MC_VOICEC:
defb $ff
MC_INTRPC:
defb $ff
MC_TEMPC:
defb $ff
MC_INTC:
defb $ff
MC_ENABLE:
defb $ff
MC_AMPLIT:
defb $ff
MC_REGIST:
defw $ffff
MC_DEFIN:
defb $ff
MC_ONAMP:
defw $ffff
MC_LPLAY:
defb $ff
;
defb $ff,$ff,$ff,$ff,$ff,$ff
MC_CHECK:
defb $00
;
defb $ff,$ff,$ff,$ff
MC_DSNAM:
defw $8000
MC_DENAM:
defw $8200
MC_HISCOR:
defw $ffff
MC_TEMP:
defb $ff
;
defb $ff,$ff
MC_RIGHTJ:
defb $ff
MC_CHANA:
defw $ffff
;
defb $ff,$ff,$ff
MC_TONEA:
defb $ff
MC_CHANB:
defw $ffff
;
defb $ff,$ff,$ff
MC_TONEB:
defb $ff
MC_CHANC:
defw $ffff
;
defb $ff,$ff,$ff
MC_TONEC:
defb $ff
MC_OBUF:
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff
MC_FILNAM:
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff
;
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff,$ff,$ff,$ff
defb $ff,$ff,$ff,$ff,$ff
; ; At position 200h different 'topics' (entries)
; ; can be defined; user can choose the topic CTRL-H
; jp start
;..on the other side the first topic can be directly
; the main program entry point, so no need for a jump table :P
ELSE
; BASIC startup mode
defw nxt_basic_line
defw 0 ; BASIC Line number
defb $a2 ; Token for CALL.
defm "992" ; this BASIC caller stub is 11 bytes long
defb 0 ; End of line
nxt_basic_line:
defw 0
ENDIF
start:
ld hl,($39)
ld (irq_hndl+1),hl
ld hl,mc_irq
ld ($39),hl
;CALL $CEBA
;LD ($0128),A
;LD ($0357),A
;LD ($0360),A
;LD ($0358),A
;LD ($0352),A
;LD ($0361),A
;DEC A
;LD ($0106),A
;LD ($0353),A
;LD ($106),a
;ld hl,$106
;ld (hl),255 ; disable gaming mode (shouldn't this work by putting 255??)
ld hl,0
add hl,sp
ld (start1+1),hl
ld hl,$bfff ; 48K ?
ld (hl),$55
ld a,$AA
or (hl)
inc a
jr z,has48k
ld hl,$3fff ; 48K.
has48k:
ld sp,hl
;ei
;xor a
;out ($80),a
;call $c021 ; setup text page (ptr in HL)
call crt0_init_bss
ld (exitsp),sp
; Optional definition for auto MALLOC init
; it assumes we have free space between the end of
; the compiled program and the stack pointer
IF DEFINED_USING_amalloc
INCLUDE "amalloc.def"
ENDIF
call _main
cleanup:
;
; Deallocate memory which has been allocated here!
;
push hl
IF !DEFINED_nostreams
EXTERN closeall
call closeall
ENDIF
pop bc
start1:
ld sp,0
IF (startup=2)
;jp $C000 ; BASIC entry (COLD RESET)
jp $C003 ; BASIC entry (WARM RESET)
ELSE
ld hl,(irq_hndl+1)
ld ($39),hl
ret
ENDIF
l_dcal:
jp (hl)
; IRQ stub to get a time counter
mc_irq:
di
push hl
push af
ld hl,(FRAMES)
inc hl
ld (FRAMES),hl
ld a,h
or l
jr nz,irq_hndl
ld hl,(FRAMES+2)
inc hl
ld (FRAMES+2),hl
irq_hndl:
ld hl,0
;jp $7f
pop af
ex (sp),hl
ret
FRAMES:
defw 0
defw 0
IF !DEFINED_nogfx
;----------- GFX init -------------
.ansi_cls
.clg
ld b,255
ld a,$9e
out ($80),a
ld hl,$8000
.clg1
ld (hl),b
inc hl
ld a,h
cp $98
jp nz,clg1
ld a,$9f
out ($80),a
ld ($f5),a ; Instruct the BASIC about the current screen mode
; so the ROM won't mess with the video page when called
ld hl,clgret
ld ($f7),hl ; cursor flashing and positioning routine
.clgret
ret
;----------- GFX support for ANSI VT emulation -------------
.ansi_SCROLLUP
ld a,$9e
out ($80),a
ld de,$8000
ld hl,$8000+256
ld bc,6144-256
ldir
ld a,23
.ansi_del_line
ex af,af
ld a,$9e
out ($80),a
ex af,af
ld hl,$8000
ld d,a ; de = line*256
ld e,l
add hl,de ;Line address in HL
ld bc,255
ld (hl),c
ld d,h
ld e,l
inc de
ldir
ld a,$9f
out ($80),a
ret
;----------- GFX paging -------------
.pixeladdress
; add y-times the nuber of bytes per line (32)
; or just multiply y by 32 and the add
ld e,l
ld a,h
ld b,a
ld h,0
add hl,hl
add hl,hl
add hl,hl
add hl,hl
add hl,hl
ld de,$8000
add hl,de
; add x divided by 8
;or a
rra
srl a
srl a
ld e,a
ld d,0
add hl,de
;-------
.gfxbyte_get
ld a,$9e
out ($80),a
ld a,(hl)
ld d,h
ld e,l
ld hl,pixelbyte
cpl
ld (hl),a
ld a,$9f
out ($80),a
ld a,b
or 0f8h ;set all unused bits 1
cpl ;they now become 0
ret
;-------
.pix_return
ex af,af ; dcircle uses the flags in af'.. watch out !
ld a,$9e
out ($80),a
ex af,af ; dcircle uses the flags in af'.. watch out !
cpl
ld (de),a ; pixel address
ld a,$9f
out ($80),a
ret
;------- ANSI VT support (chunk 1)
.pix_pre
ld a,$9e
out ($80),a
rl (ix+1)
rl (ix+0)
inc b
dec b
jr z,DTS
.L1
rl (ix+1)
rl (ix+0)
djnz L1
.DTS
;ex af,af ;
ld a,$9f
out ($80),a
;ex af,af ;
ret
;------- ANSI VT support (chunk 2)
.pix_rl
ex af,af ;
ld a,$9e
out ($80),a
ex af,af ;
.L2
rla
rl (ix+1)
rl (ix+0)
djnz L2
.pix_post
ld b,6
inc b
dec b
jr z,NEXT
.L3
rl (ix+1)
rl (ix+0)
djnz L3
.NEXT
ld a,$9f
out ($80),a
ret
ENDIF
defm "Small C+ MC1000"
defb 0
INCLUDE "crt0_runtime_selection.asm"
INCLUDE "crt0_section.asm"
SECTION bss_crt
PUBLIC pixelbyte ; Temp store for non-buffered mode
pixelbyte: defw 0
|
#ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include <cstdio>
#include "PatchConsOperator.H"
#include "FourthOrderUtil.H"
#include "CellToEdge.H"
#include "DivergenceF_F.H"
#include "NamespaceHeader.H"
//////////////////////////////////////////////////////////////////////////////
// Constructor - set up some defaults
PatchConsOperator::PatchConsOperator()
{
m_molPhysics = NULL;
m_isDefined = false;
m_isCurrentTimeSet = false;
m_isCurrentBoxSet = false;
m_dx = 0.0;
m_numFluxesPerField = 1;
}
//////////////////////////////////////////////////////////////////////////////
// Destructor - free up storage
PatchConsOperator::~PatchConsOperator()
{
if (m_molPhysics != NULL)
{
delete m_molPhysics;
}
}
//////////////////////////////////////////////////////////////////////////////
// Define the object so that time stepping can begin
void PatchConsOperator::define(
const ProblemDomain& a_domain,
const Real& a_dx,
const MOLPhysics* const a_molPhysics,
const int& a_numFields)
{
CH_TIME("PatchConsOperator::define");
// Sanity checks
CH_assert(a_dx > 0.0);
// Cache data
m_dx = a_dx;
m_domain = a_domain;
m_numFields = a_numFields;
// MOLPhysics* m_molPhysics;
m_molPhysics = a_molPhysics->new_molPhysics();
m_molPhysics->define(m_domain, m_dx);
m_numFluxes = m_molPhysics->numFluxes();
// MOLUtilities m_util;
m_util.define(m_domain, m_dx);
m_highOrderLimiter = true;
m_doDeconvolution = true;
m_noPPM = false;
m_useArtificialViscosity = false;
// Everything is defined now.
m_isDefined = true;
}
//////////////////////////////////////////////////////////////////////////////
void PatchConsOperator::setCurrentTime(const Real& a_currentTime)
{
m_currentTime = a_currentTime;
m_isCurrentTimeSet = true;
}
//////////////////////////////////////////////////////////////////////////////
void PatchConsOperator::setCurrentBox(const Box& a_currentBox)
{
m_currentBox = a_currentBox;
m_isCurrentBoxSet = true;
m_molPhysics->setCurrentBox(m_currentBox);
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::getNormalFlux(
FluxBox& a_FfaceAvg,
const FArrayBox& a_UavgFab,
Real a_weight,
bool a_setFlattening,
FArrayBox& a_flatteningFab)
{
CH_TIME("PatchConsOperator::getNormalFlux");
CH_assert(isDefined());
CH_assert(m_isCurrentBoxSet);
int numU = a_UavgFab.nComp();
CH_assert(m_numGhost >= 5);
/*
Set UcellCenFab = a_UavgFab - m_dx^2/24 * Laplacian(a_UavgFab)
on all cells of bx4inDomain = grow(m_currentBox, 4) & m_domain
using a_UavgFab
on all cells of bx5inDomain = grow(m_currentBox, 5) & m_domain.
*/
Box bx5inDomain = grow(m_currentBox, 5);
bx5inDomain &= m_domain;
Box bx4inDomain = grow(m_currentBox, 4);
bx4inDomain &= m_domain;
FArrayBox UcellCenFab(bx4inDomain, numU);
UcellCenFab.copy(a_UavgFab);
if (m_doDeconvolution)
{ // UcellCenFab -= Laplacian(a_UavgFab) * m_dx^2 / 24
// fourthOrderAverageCell(UcellCenFab, -1);
m_util.deconvolve(UcellCenFab, a_UavgFab, bx4inDomain, -1);
}
/*
Set WcellCenFab = W(UcellCenFab)
on all cells of bx4inDomain = grow(m_currentBox, 4) & m_domain
using UcellCenFab
on all cells of bx4inDomain.
*/
int numW = m_molPhysics->numConserved();
FArrayBox WcellCenFab(bx4inDomain, numW);
m_molPhysics->consToPrim(WcellCenFab, UcellCenFab, bx4inDomain);
/*
Set WofUavgFab = W(a_UavgFab)
on all cells of bx5inDomain = grow(m_currentBox, 5) & m_domain
using a_UavgFab
on all cells of bx5inDomain.
*/
FArrayBox WofUavgFab(bx5inDomain, numW);
m_molPhysics->consToPrim(WofUavgFab, a_UavgFab, bx5inDomain);
/*
Set WcellAvgFab = WofUavgFab + m_dx^2/24 * Laplacian(WofUavgFab)
on all cells of bx4inDomain = grow(m_currentBox, 4) & m_domain
using WofUavgFab
on all cells of bx5inDomain = grow(m_currentBox, 5) & m_domain.
*/
FArrayBox WcellAvgFab(bx4inDomain, numW);
WcellAvgFab.copy(WcellCenFab);
if (m_doDeconvolution)
{
// deconvolve(WcellAvgFab, WcellCenFab);
m_util.deconvolve(WcellAvgFab, WofUavgFab, bx4inDomain);
}
Box bx1 = grow(m_currentBox, 1);
Box bx1inDomain(bx1);
bx1inDomain &= m_domain;
FluxBox WfaceAvg(bx1inDomain, numW);
/*
Set WfaceAvg
on all faces of bx1inDomain = grow(m_currentBox, 1) & m_domain,
using WcellAvgFab
on bx4inDomain = grow(m_currentBox, 4) & m_domain,
and WofUavgFab
on bx4inDomain = grow(m_currentBox, 4) & m_domain,
and a_flatteningFab
on bx1inDomain.
Fourth-order interpolation:
WfaceAvg[i+e/2] = 7/12 * (WcellAvgFab[i] + WcellAvgFab[i+e])
- 1/12 * (WcellAvgFab[i-e] + WcellAvgFab[i+2e]).
Includes calls to limiter (if used) and flattening (if used),
and Riemann solver.
*/
getFaceAvg(WfaceAvg, WcellAvgFab, WofUavgFab,
a_flatteningFab, a_setFlattening);
/*
Set WfaceCen = WfaceAvg - m_dx^2/24 * Laplacian(WfaceAvg)
on all faces of m_currentBox
using WfaceAvg
on all faces of bx1inDomain = grow(m_currentBox, 1) & m_domain.
*/
FluxBox WfaceCen(m_currentBox, numW);
// First set WfaceCen = WfaceAvg.
WfaceCen.copy(WfaceAvg);
// Then set WfaceCen -= Laplacian(WfaceAvg) * m_dx^2 / 24
// on all faces of m_currentBox
// using WfaceAvg
// on all faces of m_currentBox.
// Special stencils next to boundary of m_domain.
m_util.deconvolveFace(WfaceCen, WfaceAvg, m_currentBox, -1);
/*
Set a_FfromWfaceAvg = F(WfaceAvg)
on all faces of bx1inDomain = grow(m_currentBox, 1) & m_domain
using WfaceAvg
on all faces of bx1inDomain.
Set FfaceCen = F(WfaceCen)
on all faces of m_currentBox
using WfaceCen
on all faces of m_currentBox.
*/
FluxBox FfaceCen(m_currentBox, m_numFluxesPerField * m_numFluxes);
FluxBox FfromWfaceAvg(bx1, m_numFluxesPerField * m_numFluxes);
getAllFluxes(FfromWfaceAvg, FfaceCen, WfaceAvg, WfaceCen);
a_FfaceAvg.define(bx1inDomain, m_numFluxesPerField * m_numFluxes);
if (m_doFaceDeconvolution)
{
/*
Set a_FfaceAvg = FfaceCen + m_dx^2/24 * Laplacian(FfromWfaceAvg)
on all idir-faces of m_currentBox
using FfaceCen
on all idir-faces of m_currentBox
and original a_FfaceAvg
on all idir-faces of bx1inDomain = grow(m_currentBox, 1) & m_domain.
*/
// First set a_FfaceAvg = FfaceCen = flux(WfaceCen)
// on all faces of m_currentBox.
a_FfaceAvg.copy(FfaceCen);
// Then set a_FfaceAvg += Laplacian(FfromWfaceAvg) * m_dx^2 / 24
// on all faces of m_currentBox,
// using FfromWfaceAvg
// on all faces of bx1inDomain = grow(m_currentBox, 1) & m_domain.
// Special stencils next to boundary of m_domain.
m_util.deconvolveFace(a_FfaceAvg, FfromWfaceAvg, m_currentBox);
}
else
{
a_FfaceAvg.copy(FfromWfaceAvg);
}
reduceFlux(a_FfaceAvg, FfromWfaceAvg);
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::reduceFlux(FluxBox& a_FfaceAvg,
FluxBox& a_FfaceForGrad)
{
// This function intentionally left blank.
// Derived classes may use it.
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::getFluxDivergence(FArrayBox& a_LofU,
const FluxBox& a_FfaceAvg)
{
CH_TIME("PatchConsOperator::getFluxDivergence");
a_LofU.setVal(0.0);
for (int idir = 0; idir < SpaceDim; idir++)
{
const FArrayBox& currentFluxDir = a_FfaceAvg[idir];
// Increment a_LofU on all cells of m_currentBox
// using a_FfaceAvg[idir] on all idir-faces of m_currentBox.
FORT_DIVERGENCE(CHF_CONST_FRA(currentFluxDir),
CHF_FRA(a_LofU),
CHF_BOX(m_currentBox),
CHF_CONST_REAL(m_dx),
CHF_INT(idir));
// dummy statement in order to get around gdb bug
int dummy_unused = 0; dummy_unused = 0;
}
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::getAllFluxes(FluxBox& a_FfaceAvg,
FluxBox& a_FfaceCen,
const FluxBox& a_WfaceAvg,
const FluxBox& a_WfaceCen)
{
CH_TIME("PatchConsOperator::getAllFluxes");
CH_assert(m_isCurrentBoxSet);
Box bx1inDomain = grow(m_currentBox, 1);
bx1inDomain &= m_domain;
for (int idir = 0; idir < SpaceDim; idir++)
{ // idir specifies which faces: either x or y or z
Box faceBox1(bx1inDomain);
faceBox1.surroundingNodes(idir);
const FArrayBox& WfaceAvgDir = a_WfaceAvg[idir];
FArrayBox& FfaceAvgDir = a_FfaceAvg[idir];
// Set FfaceAvgDir = flux(WfaceAvgDir)
// on all idir-faces of bx1inDomain = grow(m_currentBox, 1) & m_domain.
m_molPhysics->getFlux(FfaceAvgDir, WfaceAvgDir, idir, faceBox1);
if (m_doFaceDeconvolution)
{ // otherwise, a_FfaceCen is UNUSED.
Box faceBox0(m_currentBox);
faceBox0.surroundingNodes(idir);
const FArrayBox& WfaceCenDir = a_WfaceCen[idir];
FArrayBox& FfaceCenDir = a_FfaceCen[idir];
// Set FfaceCenDir = flux(WfaceCenDir)
// on all idir-faces of m_currentBox
// using WfaceCenDir
// on all idir-faces of m_currentBox.
m_molPhysics->getFlux(FfaceCenDir, WfaceCenDir, idir, faceBox0);
}
}
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::updateODE(FArrayBox& a_solnFab,
const FArrayBox& a_rhsFab,
Real a_dt)
{
CH_TIME("PatchConsOperator::updateODE");
int rhsComp = a_rhsFab.nComp();
CH_assert(a_solnFab.nComp() == rhsComp);
const Box& bx = a_rhsFab.box();
a_solnFab.plus(a_rhsFab, bx, bx, a_dt, 0, 0, rhsComp);
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::getFaceAvg(// we'll apply limiter to a_faceW
FluxBox& a_faceW,
const FArrayBox& a_cellW,
const FArrayBox& a_WofUavg,
FArrayBox& a_flatteningFab,
bool a_setFlattening)
{
CH_TIME("PatchConsOperator::getFaceAvg");
CH_assert(isDefined());
CH_assert(m_isCurrentBoxSet);
int nComp = a_faceW.nComp();
Box bx1inDomain = grow(m_currentBox, 1);
bx1inDomain &= m_domain;
// Flattening stencil has size 3.
// Compute flattening once for all slopes if needed.
// Each CELL has a flattening coefficient, eta.
// Flattening means replacing Wface on left and right of each cell
// by eta*Wface + (1-eta)*Wcell.
// = Wcell + eta * (Wface - Wcell).
// That is:
// WfaceL[+] = Wcell + eta * (WfaceL[+] - Wcell);
// WfaceR[-] = Wcell + eta * (WfaceR[-] - Wcell).
if (m_useFlattening && a_setFlattening)
{
Interval velInt = m_molPhysics->velocityInterval();
int pressureInd = m_molPhysics->pressureIndex();
Real smallPressure = m_molPhysics->smallPressure();
int bulkInd = m_molPhysics->bulkModulusIndex();
// Set a_flatteningFab
// on all cells of bx1inDomain = grow(m_currentBox, 1) & m_domain
// using a_WofUavg
// on all cells of bx4inDomain = grow(m_currentBox, 4) & m_domain.
const Box& flatteningBox = a_flatteningFab.box();
CH_assert(flatteningBox == bx1inDomain);
m_util.computeFlattening(a_flatteningFab, a_WofUavg,
velInt, pressureInd, smallPressure, bulkInd,
flatteningBox);
}
for (int idir = 0; idir < SpaceDim; idir++)
{
// thisFaceWDir lives on idir-FACEs.
FArrayBox& thisFaceWDir = a_faceW[idir];
const Box& faceBox = thisFaceWDir.box();
if (!m_noPPM) // if (m_noPPM) then set thisFaceWDir later.
{
/*
Set thisFaceWDir from a_cellW by 4th-order interpolation
on all idir-faces of bx1inDomain = grow(m_currentBox, 1) & m_domain
using a_cellW on bx4inDomain = grow(m_currentBox, 4) & m_domain
with the formula
thisFaceWDir[i+e/2] = 7/12 * (a_cellW[i] + a_cellW[i+e])
- 1/12 * (a_cellW[i-e] + a_cellW[i+2e]).
*/
m_util.PPMFaceValues(thisFaceWDir, a_cellW, nComp, m_limitFaceValues,
idir, faceBox, m_currentTime, m_molPhysics);
}
/*
On domain boundaries, set thisFaceWDir to a_cellW.
*/
if (!m_domain.isPeriodic(idir))
{
PhysIBC* bc = m_molPhysics->getPhysIBC();
for (SideIterator sit; sit.ok(); ++sit)
{
Side::LoHiSide side = sit();
int isign = sign(side);
Box boundaryBox;
bc->getBoundaryFaces(boundaryBox, thisFaceWDir.box(), idir, side);
boundaryBox.shiftHalf(idir, -isign);
thisFaceWDir.shiftHalf(idir, -isign);
thisFaceWDir.copy(a_cellW, boundaryBox);
thisFaceWDir.shiftHalf(idir, isign);
}
}
if (m_limitFaceValues || m_useFlattening || m_noPPM)
{
FArrayBox WMinus(bx1inDomain, nComp);
FArrayBox WPlus( bx1inDomain, nComp);
// Set WMinus = thisFaceWDir[-idir/2] - a_cellW
// on all cells of bx1inDomain = grow(m_currentBox, 1) & m_domain
// using thisFaceWDir
// on idir-faces of bx1inDomain except highest face
// and a_cellW
// on all cells of bx1inDomain.
// Set WPlus = thisFaceWDir[+idir/2] - a_cellW
// on all cells of bx1inDomain = grow(m_currentBox, 1) & m_domain
// using thisFaceWDir
// on idir-faces of bx1inDomain except lowest face
// and a_cellW
// on all cells of bx1inDomain.
WMinus.setVal(0.);
WPlus .setVal(0.);
if (!m_noPPM)
{
// WMinus -= a_cellW;
// WPlus -= a_cellW;
// Call minus() instead of the simpler -= because
// the domains do not match.
WMinus.minus(a_cellW, bx1inDomain, 0, 0, nComp);
WPlus.minus( a_cellW, bx1inDomain, 0, 0, nComp);
// WMinus[i] = thisFaceWDir[i - e/2] - a_cellW[i]
// WPlus[i] = thisFaceWDir[i + e/2] - a_cellW[i]
thisFaceWDir.shiftHalf(idir, +1); // [i-e/2] becomes [i]
WMinus.plus(thisFaceWDir, bx1inDomain, 0, 0, nComp);
thisFaceWDir.shift(idir, -1); // [i+e/2] becomes [i]
WPlus.plus( thisFaceWDir, bx1inDomain, 0, 0, nComp);
thisFaceWDir.shiftHalf(idir, +1); // final shift back
if (m_limitFaceValues)
{
// Note: petermc, 21 Sep 2010, changed from 2 layers to 3,
// with the new check-cubic limiter.
// Apply limiter to WMinus and WPlus
// on all cells of bx1inDomain = grow(m_currentBox, 1) & m_domain
// using a_cellW
// on bx4inDomain = grow(m_currentBox, 4) & m_domain.
// Recall:
// WMinus[i] = thisFaceWDir[i - e/2] - a_cellW.
// WPlus[i] = thisFaceWDir[i + e/2] - a_cellW.
m_util.PPMLimiter(WMinus, WPlus, a_cellW, nComp, idir, bx1inDomain);
}
if (m_useFlattening)
{
// Multiply WMinus and WPlus by a_flatteningFab
// on all cells of bx1inDomain = grow(m_currentBox, 1) & m_domain.
m_util.applyFlattening(WMinus, a_flatteningFab, bx1inDomain);
m_util.applyFlattening(WPlus, a_flatteningFab, bx1inDomain);
}
} // if (!m_noPPM)
// WMinus[i] = thisFaceWDir[i-e/2] on right after limiting
// WMinus += a_cellW;
// WPlus[i] = thisFaceWDir[i+e/2] on left after limiting
// WPlus += a_cellW;
WMinus.plus(a_cellW, bx1inDomain, 0, 0, nComp);
WPlus.plus( a_cellW, bx1inDomain, 0, 0, nComp);
// If m_noPPM then WMinus == a_cellW == WPlus,
// and we fill in thisFaceWDir by solving Riemann problem.
// Now solve Riemann problem.
// Modify thisFaceWDir[i + e/2] based on
// WPlus[i] = WleftExtrap[i + e/2] and
// WMinus[i + e] = WrightExtrap[i + e/2].
// Solve Riemann problem:
// Set thisFaceWDir
// on interior idir-faces of bx1inDomain = grow(m_currentBox, 1) & m_domain
// using WPlus and WMinus
// on cells of bx1inDomain.
Box riemannBox(bx1inDomain);
riemannBox.surroundingNodes(idir);
riemannBox.grow(idir, -1);
// The riemann() function also sets boundary conditions
// on thisFaceWDir, even though the external boundary faces
// are NOT in riemannBox.
// The riemann() function also transforms velocities.
preRiemann(WPlus, WMinus, idir, riemannBox);
m_molPhysics->riemann(thisFaceWDir, // on idir-FACEs
WPlus, // on CELLs to left of idir-FACEs
WMinus, // on CELLs to right of idir-FACEs
a_cellW, // used? on CELLs
m_currentTime,
idir,
riemannBox); // on idir-FACEs
postRiemann(thisFaceWDir, idir, riemannBox);
// dummy statement in order to get around gdb bug
int dummy_unused = 0; dummy_unused = 0;
}
else
{ // neither limiting nor flattening,
// therefore call Riemann solver only on physical boundary.
PhysIBC* bc = m_molPhysics->getPhysIBC();
for (SideIterator sit; sit.ok(); ++sit)
{
Side::LoHiSide side = sit();
Box boundaryBox;
// bc->getBoundaryFaces(boundaryBox, faceBox, idir, side);
// changed by petermc, 16 Mar 2010
bc->getBoundaryFaces(boundaryBox, thisFaceWDir.box(), idir, side);
if (! boundaryBox.isEmpty() )
{
FArrayBox WPlusOrMinus(boundaryBox, nComp); // on FACEs
WPlusOrMinus.copy(thisFaceWDir, boundaryBox);
// This will fill in thisFaceWDir on boundaryBox only:
// it recalculates boundaryBox from thisFaceWDir.box().
// Notice:
// thisFaceWDir and WPlusOrMinus are FACE-centered;
// a_cellW is CELL-centered. Derived classes know this.
// They call Fortran subroutines that also know this.
bc->primBC(thisFaceWDir,
WPlusOrMinus, a_cellW, idir, side, m_currentTime);
}
}
}
} // end loop over directions
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::preRiemann(FArrayBox& a_WLeft,
FArrayBox& a_WRight,
int a_dir,
const Box& a_box)
{
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::postRiemann(FArrayBox& a_Wface,
int a_dir,
const Box& a_box)
{
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::spaceOrder(int a_spaceOrder)
{
m_spaceOrder = a_spaceOrder;
}
void
PatchConsOperator::limitFaceValues(bool a_limitFaceValues)
{
m_limitFaceValues = a_limitFaceValues;
}
void
PatchConsOperator::highOrderLimiter(bool a_highOrderLimiter)
{
m_highOrderLimiter = a_highOrderLimiter;
m_util.highOrderLimiter(m_highOrderLimiter);
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::useFlattening(bool a_useFlattening)
{
m_useFlattening = a_useFlattening;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::noPPM(bool a_noPPM)
{
m_noPPM = a_noPPM;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::doDeconvolution(bool a_doDeconvolution)
{
m_doDeconvolution = a_doDeconvolution;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::doFaceDeconvolution(bool a_doFaceDeconvolution)
{
m_doFaceDeconvolution = a_doFaceDeconvolution;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::useArtificialViscosity(bool a_useArtificialViscosity)
{
m_useArtificialViscosity = a_useArtificialViscosity;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::artificialViscosity(Real a_artificialViscosity)
{
m_artificialViscosity = a_artificialViscosity;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::numGhost(int a_numGhost)
{
m_numGhost = a_numGhost;
}
//////////////////////////////////////////////////////////////////////////////
void
PatchConsOperator::addArtificialViscosity(FArrayBox& a_UnewFab,
const FArrayBox& a_UoldFab,
FluxBox& a_flux,
Real a_weight)
{
CH_TIME("PatchConsOperator::addArtificialViscosity");
CH_assert(isDefined());
CH_assert(m_useArtificialViscosity);
CH_assert(m_isCurrentBoxSet);
Box bx1inDomain = grow(m_currentBox, 1);
bx1inDomain &= m_domain;
a_flux.define(m_currentBox, m_numFluxes);
FArrayBox divFlux(m_currentBox, a_UnewFab.nComp());
divFlux.setVal(0.);
for (int idir = 0; idir < SpaceDim; idir++)
{
FArrayBox& currentFluxDir = a_flux[idir];
currentFluxDir.setVal(0.);
// Increment a_flux[idir]
// on all idir-faces of m_currentBox
// using a_UoldFab
// on all cells of bx1inDomain = grow(a_box, 1) & m_domain.
m_molPhysics->artVisc(currentFluxDir,
a_UoldFab,
m_artificialViscosity,
m_currentTime,
idir,
m_currentBox);
// Increment divFlux on all cells of m_currentBox
// using a_flux[idir] on all idir-faces of m_currentBox.
FORT_DIVERGENCE(CHF_CONST_FRA(currentFluxDir),
CHF_FRA(divFlux),
CHF_BOX(m_currentBox),
CHF_CONST_REAL(m_dx),
CHF_INT(idir));
// dummy statement in order to get around gdb bug
int dummy_unused = 0; dummy_unused = 0;
}
a_UnewFab.plus(divFlux, -a_weight);
// Now LevelConsOperator needs to increment m_fluxes and flux registers.
}
//////////////////////////////////////////////////////////////////////////////
bool PatchConsOperator::isDefined() const
{
return m_isDefined &&
m_isCurrentTimeSet &&
m_isCurrentBoxSet ;
}
#include "NamespaceFooter.H"
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) Geoworks 1994 -- All Rights Reserved
PROJECT: ConView Library
MODULE: Main
FILE: mainSpecialLink.asm
AUTHOR: Cassie Hartzog, January 26, 1995
MESSAGES:
ROUTINES:
Name Description
---- -----------
INT MSLHandleSpecialLink Looks for and handles special links.
REVISION HISTORY:
Name Date Description
---- ---- -----------
Cassie 1/26/95 Initial revision
DESCRIPTION:
Code needed for dealing with special hyperlinks.
$Id: mainSpecialLink.asm,v 1.1 97/04/04 17:49:41 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
;
; First, some useful macros.
;
ClrZero macro
mov ax, 1
or ax, ax ; clear zero flag
endm
SetZero macro
xor ax, ax ; clear zero flag
endm
BookFileCode segment resource
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLHandleSpecialLink
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Look for and handle special hyperlinks
CALLED BY: CGVFollowLinkLow
PASS: *ds:si - ContentGenView
ss:bp - ContentTextRequest
RETURN: Z flag - clear if caller needs to follow link in CTR,
(CTR_context may have been modified)
- set if caller shouldn't follow link
DESTROYED: anything but ds, si, bp may be destroyed
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLHandleSpecialLink proc near
cmp {tchar}ss:[bp].CTR_context, '!'
je handleSpecial
ret
handleSpecial:
;
; The next char tells us what kind of special link this is.
;
SBCS < mov al, ss:[bp].CTR_context.[1] >
SBCS < sub al, ' ' >
DBCS < mov ax, ss:[bp].CTR_context.[1] >
DBCS < sub ax, ' ' >
EC < WARNING_S INVALID_SPECIAL_LINK_CHAR >
js done
SBCS < cmp al, length specialLinkHandlerTable >
DBCS < cmp ax, length specialLinkHandlerTable >
EC < WARNING_A INVALID_SPECIAL_LINK_CHAR >
ja done
;
; Find the special handler's offset in the table below
;
SBCS < clr ah >
shl ax ; word align the index
mov bx, ax
EC < swatLabel:: >
call cs:specialLinkHandlerTable[bx]
done:
ret
MSLHandleSpecialLink endp
;
; This table is indexed by the PC GEOS character set.
;
specialLinkHandlerTable nptr.near \
DefaultLinkHandler, ; C_SPACE
DefaultLinkHandler, ; '!'
DefaultLinkHandler, ; '"'
DefaultLinkHandler, ; '#'
DefaultLinkHandler, ; '$'
DefaultLinkHandler, ; '%'
DefaultLinkHandler, ; '&'
DefaultLinkHandler, ; '''
DefaultLinkHandler, ; '('
DefaultLinkHandler, ; ')'
DefaultLinkHandler, ; '*'
DefaultLinkHandler, ; '+'
DefaultLinkHandler, ; ','
DefaultLinkHandler, ; '-'
DefaultLinkHandler, ; '.'
DefaultLinkHandler, ; '/'
MSLStandardSoundError, ; '0'
MSLStandardSoundWarning, ; '1'
MSLStandardSoundNotify, ; '2'
MSLStandardSoundNoInput, ; '3'
MSLStandardSoundKeyClick, ; '4'
MSLStandardSoundAlarm, ; '5'
DefaultLinkHandler, ; '6'
DefaultLinkHandler, ; '7'
DefaultLinkHandler, ; '8'
DefaultLinkHandler, ; '9'
DefaultLinkHandler, ; ':'
DefaultLinkHandler, ; ';'
DefaultLinkHandler, ; '<'
DefaultLinkHandler, ; '='
DefaultLinkHandler, ; '>'
DefaultLinkHandler, ; '?'
DefaultLinkHandler, ; '@'
MSLLaunchApplicationAndQuit, ; 'A'
MSLGoBack, ; 'B'
DefaultLinkHandler, ; 'C'
DefaultLinkHandler, ; 'D'
DefaultLinkHandler, ; 'E'
DefaultLinkHandler, ; 'F'
DefaultLinkHandler, ; 'G'
MSLInvertHotspots, ; 'H'
DefaultLinkHandler, ; 'I'
DefaultLinkHandler, ; 'J'
DefaultLinkHandler, ; 'K'
DefaultLinkHandler, ; 'L'
DefaultLinkHandler, ; 'M'
MSLNextPage, ; 'N'
DefaultLinkHandler, ; 'O'
MSLPreviousPage, ; 'P'
MSLQuitBookReader, ; 'Q'
DefaultLinkHandler, ; 'R'
;;; MSLPlaySoundAndLink, ; 'S' - doesn't work yet!
DefaultLinkHandler, ; 'S'
MSLGotoTOC, ; 'T'
DefaultLinkHandler, ; 'U'
DefaultLinkHandler, ; 'V'
DefaultLinkHandler, ; 'W'
DefaultLinkHandler, ; 'X'
DefaultLinkHandler, ; 'Y'
DefaultLinkHandler, ; 'Z'
DefaultLinkHandler, ; '['
DefaultLinkHandler, ; '\'
DefaultLinkHandler, ; ']'
DefaultLinkHandler, ; '^'
DefaultLinkHandler, ; '_'
DefaultLinkHandler, ; '`'
MSLLaunchApplication, ; 'a'
DefaultLinkHandler, ; 'b'
DefaultLinkHandler, ; 'c'
DefaultLinkHandler, ; 'd'
DefaultLinkHandler, ; 'e'
DefaultLinkHandler, ; 'f'
DefaultLinkHandler, ; 'g'
DefaultLinkHandler, ; 'h'
DefaultLinkHandler, ; 'i'
DefaultLinkHandler, ; 'j'
DefaultLinkHandler, ; 'k'
DefaultLinkHandler, ; 'l'
DefaultLinkHandler, ; 'm'
DefaultLinkHandler, ; 'n'
DefaultLinkHandler, ; 'o'
DefaultLinkHandler, ; 'p'
DefaultLinkHandler, ; 'q'
DefaultLinkHandler, ; 'r'
;;; MSLPlaySound, ; 's' - doesn't work yet!
DefaultLinkHandler, ; 's'
DefaultLinkHandler, ; 't'
DefaultLinkHandler, ; 'u'
DefaultLinkHandler, ; 'v'
DefaultLinkHandler, ; 'w'
DefaultLinkHandler, ; 'x'
DefaultLinkHandler, ; 'y'
DefaultLinkHandler, ; 'z'
DefaultLinkHandler, ; '{'
DefaultLinkHandler, ; '|'
DefaultLinkHandler, ; '}'
DefaultLinkHandler ; '~'
.assert (length specialLinkHandlerTable eq ('~' - ' ')+1)
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
DefaultLinkHandler
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Clear zero flag, so that link is handled normally
by CGVFollowLinkLow.
CALLED BY: MSLHandleSpecialLink
PASS: nothing
RETURN: Z flag is clear, so that link is treated normally
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
DefaultLinkHandler proc near
mov ax, 1
or ax, ax ; clear zero flag
ret
DefaultLinkHandler endp
if 0 ; this doesn't work yet
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLPlaySoundAndLink
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Play a .wav file whose name follows the ! in CTR_context,
and is terminated by a '.', and is followed by the NULL-
termianted name of a link to follow after playing the sound.
CALLED BY:
PASS: ss:bp - ContentTextRequest
RETURN: Z flag clear if there is a link name following the wav filename
Z flag set if no link name
DESTROYED: ax, cx, es, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLPlaySoundAndLink proc near
uses si
.enter
;
; Look for the '.' which terminates the wav filename
; and replace it with a NULL.
;
segmov es, ss, ax
lea di, ss:[bp].CTR_context
mov cx, CONTEXT_NAME_BUFFER_SIZE
sub cx, (size tchar) * 2 ; sub NULL and '!S'
DBCS < mov ax, '.' >
SBCS < mov ax, '.' >
LocalFindChar
jnz playSound ; '.' not found!
sub di, size tchar
mov {tchar}es:[di], C_NULL
playSound:
pushf
push di ; save offset to link
call MSLPlaySound
pop si ; ds:si <- link name
popf
jnz noLink ; is there a link?
;
; Move the link name to the front of CTR_context
;
lea di, ss:[bp].CTR_context ; es:di - dest
segmov es, ds, ax
LocalCopyString
ClrZero ; do follow the link
done:
.leave
ret
noLink:
SetZero
jmp done
MSLPlaySoundAndLink endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLPlaySound
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Play a .wav file whose name follows the ! in CTR_context
and is NULL-terminated.
CALLED BY:
PASS: ss:bp - ContentTextRequest
RETURN: Zero set
DESTROYED: ax, bx, di, es
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
standardWavExtension tchar ".wav",0
MSLPlaySound proc near
uses si, ds
.enter
;
; Save The current directory, go to the book's directory
;
call FilePushDir
call MFChangeToBookDirectory
;
; Copy the wav filename, which follows the '!' char, to our buffer
; and tack on the ".wav" extension.
;
sub sp, size FileLongName
mov di, sp
segmov es, ss, ax ; es:di <- filename buffer
mov ds, ax
lea si, {tchar}ss:[bp].CTR_context.[2]
LocalCopyString
sub di, size tchar ; point to the null
segmov ds, cs, ax
mov si, offset standardWavExtension
LocalCopyString
mov di, sp ; es:di <- wav filename
; Play the .wav file.
clr bx
mov {tchar}ss:[bp].CTR_context, 0
lea dx, ss:[bp].CTR_context
call WavPlayFile
call FilePopDir
add sp, size FileLongName
SetZero ; don't follow any link!
.leave
ret
MSLPlaySound endp
endif
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLInvertHotspots
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Causes the hotspots on the current page to toggle
invert themselves.
CALLED BY:
PASS: *ds:si - ContentGenView
RETURN: Zero flag set
DESTROYED: ax, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLInvertHotspots proc near
mov ax, MSG_CT_TOGGLE_INVERT_AND_INVERT
clr di
call MUObjMessageSend
SetZero
ret
MSLInvertHotspots endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLLaunchApplicationAndQuit
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS:
CALLED BY:
PASS:
RETURN: Zero flag set
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLLaunchApplicationAndQuit proc near
call MSLLaunchApplication
jcxz done
GOTO MSLQuitBookReader
done:
ret
MSLLaunchApplicationAndQuit endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLLaunchApplication
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Launch an application
CALLED BY:
PASS: nada
RETURN: cx - non-zero app was successfully launched, as far as
we can tell
- 0 if error finding or launching app
Zero flag set
DESTROYED: ax, bx, cx, dx, di, es
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
changes to App directory
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLLaunchApplication proc near
uses si, ds
.enter
;
; Copy the app's token chars to a buffer
;
segmov ds, ss, ax
mov es, ax
sub sp, size GeodeToken
mov di, sp ; es:di <- buffer
lea si, ss:[bp].CTR_context.[2] ; ds:si <- TokenChars
mov cx, size TokenChars
rep movsb
xchg si, di ;ds:di<-manufID string
call LocalAsciiToFixed ;dx <- ManufID
mov es:[si], dx
mov di, sp ;es:di <- GeodeToken
;
; Create a launch block for IACP.
;
mov dx, MSG_GEN_PROCESS_OPEN_APPLICATION
call IACPCreateDefaultLaunchBlock
mov bx, dx
jc error
;
; Launch app using IACP.
;
push bp
mov ax, mask IACPCF_FIRST_ONLY or \
mask IACPCF_OBEY_LAUNCH_MODEL or \
(IACPSM_USER_INTERACTIBLE shl offset IACPCF_SERVER_MODE)
call IACPConnect
mov dx, ax
mov_tr ax, bp
pop bp
jc error
push bp
mov_tr bp, ax
clr cx, dx
call IACPShutdown
pop bp
mov cx, 1 ; no error
done:
add sp, size GeodeToken
SetZero
.leave
ret
error:
clr cx ; return error
jmp done
MSLLaunchApplication endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLQuitBookReader
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Shuts down the app
CALLED BY:
PASS: nothing
RETURN: Zero flag set
DESTROYED: ax, bx, cx, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLQuitBookReader proc near
mov ax, MSG_META_QUIT
call UserSendToApplicationViaProcess
SetZero
ret
MSLQuitBookReader endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLStandardSound.....
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Play a standard sound and optionally follow a link,
if one follows the special hyperlink chars.
CALLED BY:
PASS: ss:bp - ContentTextRequest
RETURN: Z flag clear if there is a link name, now in CTR_context
Z flag set if no link name
DESTROYED:
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLStandardSoundError proc near
mov ax, SST_ERROR
GOTO callUserStandardSound
MSLStandardSoundError endp
MSLStandardSoundWarning proc near
mov ax, SST_WARNING
GOTO callUserStandardSound
MSLStandardSoundWarning endp
MSLStandardSoundNotify proc near
mov ax, SST_NOTIFY
GOTO callUserStandardSound
MSLStandardSoundNotify endp
MSLStandardSoundNoInput proc near
mov ax, SST_NO_INPUT
GOTO callUserStandardSound
MSLStandardSoundNoInput endp
MSLStandardSoundKeyClick proc near
mov ax, SST_KEY_CLICK
GOTO callUserStandardSound
MSLStandardSoundKeyClick endp
MSLStandardSoundAlarm proc near
mov ax, SST_ALARM
FALL_THRU callUserStandardSound
MSLStandardSoundAlarm endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
callUserStandardSound
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Play the sound and look for a link name following the
special hyperlink chars.
CALLED BY:
PASS: *ds:si - ConGenView
RETURN: Z flag clear if there is a link name, now in CTR_context
Z flag set if no link name
DESTROYED: ax, di, es
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
callUserStandardSound proc near
uses ds, si
.enter
call UserStandardSound
cmp {tchar}ss:[bp].CTR_context.[2], 0
jz done
;
; Move the link name to the front of CTR_context
;
lea di, ss:[bp].CTR_context ; es:di <- dest
mov si, di
add si, (size tchar) * 2 ; move past !x
segmov es, ss, ax
mov ds, ax
LocalCopyString
ClrZero ; do follow the link
done:
.leave
ret
callUserStandardSound endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLGoBack
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Send a message to go back to previously viewed page
CALLED BY: MSLHandleSpecialLink
PASS: nothing
RETURN: Z flag is set
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLGoBack proc near
;
; Send a "go back" message to the nav controller.
;
mov ax, MSG_CNC_GO_BACK
GOTO SendMsgToCNCAndSetZFlag
MSLGoBack endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLGotoTOC
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Send a message to goto the TOC
CALLED BY: MSLHandleSpecialLink
PASS: nothing
RETURN: Z flag is set
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLGotoTOC proc near
;
; Send a "goto TOC" message to the nav controller.
;
mov ax, MSG_CNC_GOTO_TOC
GOTO SendMsgToCNCAndSetZFlag
MSLGotoTOC endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLNextPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Send a "goto next page" message to the nav controller.
CALLED BY: MSLHandleSpecialLink
PASS: nothing
RETURN: Z flag is set
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLNextPage proc near
;
; Send a "goto next page" message to the nav controller.
;
mov ax, MSG_CNC_NEXT_PAGE
GOTO SendMsgToCNCAndSetZFlag
MSLNextPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
MSLPreviousPage
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Send a "goto next page" message to the nav controller.
CALLED BY: MSLHandleSpecialLink
PASS: nothing
RETURN: Z flag is set
DESTROYED: ax
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
MSLPreviousPage proc near
;
; Send a "goto next page" message to the nav controller.
;
mov ax, MSG_CNC_PREVIOUS_PAGE
GOTO SendMsgToCNCAndSetZFlag
MSLPreviousPage endp
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SendMsgToCNCAndSetZFlag
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
SYNOPSIS: Force queue a message to ContentNavControl
CALLED BY: INT - utility
PASS: ax - message to send
*ds:si - ContentGenView
RETURN: Zero flag is set
DESTROYED: ax, bx, si, di
PSEUDO CODE/STRATEGY:
KNOWN BUGS/SIDE EFFECTS/IDEAS:
REVISION HISTORY:
Name Date Description
---- ---- -----------
cassie 1/26/95 Initial version
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
SendMsgToCNCAndSetZFlag proc near
; record the passed message, which goes to ContentNavControl
push si
mov bx, segment ContentNavControlClass
mov si, offset ContentNavControlClass
mov di, mask MF_RECORD
call ObjMessage
mov cx, di
; record a classed event, which is sent to...
mov bx, segment ContentNavControlClass
mov si, offset ContentNavControlClass
mov ax, MSG_META_SEND_CLASSED_EVENT
mov dx, TO_SELF
mov di, mask MF_RECORD
call ObjMessage
mov cx, di
pop si
; the process, which will see that this message makes it
; to the NavControl.
mov ax, MSG_GEN_SEND_TO_PROCESS
call ObjCallInstanceNoLock
SetZero
ret
SendMsgToCNCAndSetZFlag endp
BookFileCode ends
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "EZOnlineFunctionLibrary.h"
#include "IPAddress.h"
#include "SocketSubsystem.h"
#include "Engine/Engine.h"
#include "Engine/GameInstance.h"
#include "Engine/World.h"
#include "Engine/LocalPlayer.h"
#include "OnlineSubsystemTypes.h"
#include "GameFramework/GameMode.h"
#include "EZOnlineGameInstance.h"
#include "Engine.h"
#if PLATFORM_WINDOWS
#include "AllowWindowsPlatformTypes.h"
#endif
#if WITH_EDITOR
#include "Editor.h"
#endif
/*void UEZOnlineFunctionLibrary::SetPlayerUniqueNetId(APlayerController* playerController, const FString& strUniqueNetId)
{
ULocalPlayer* localPlayer = playerController->GetLocalPlayer();
localPlayer->SetCachedUniqueNetId(MakeShareable(new FUniqueNetIdString(strUniqueNetId)));
}*/
int UEZOnlineFunctionLibrary::GetWorldPort(const UObject* WorldContextObject)
{
UWorld* World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject);
if (!World)
{
return 0;
}
UGameInstance* pGameInstance = World->GetGameInstance();
if (pGameInstance)
{
FWorldContext* pWorldContext = pGameInstance->GetWorldContext();
if (pWorldContext->LastURL.Valid)
{
return pWorldContext->LastURL.Port;
}
}
return 0;
}
int UEZOnlineFunctionLibrary::GetZoneID(const UObject* WorldContextObject)
{
UEZOnlineGameInstance* pGameInstance = Cast<UEZOnlineGameInstance>(UGameplayStatics::GetGameInstance(WorldContextObject) );
if (pGameInstance == nullptr)
{
return 0;
}
return pGameInstance->mAccountSaveGame->ZoneId;
}
void UEZOnlineFunctionLibrary::SetZoneID(const UObject* WorldContextObject, int iZoneID)
{
UEZOnlineGameInstance* pGameInstance = Cast<UEZOnlineGameInstance>(UGameplayStatics::GetGameInstance(WorldContextObject));
if (pGameInstance == nullptr)
{
return;
}
pGameInstance->mAccountSaveGame->ZoneId = iZoneID;
pGameInstance->SaveAccount();
}
void UEZOnlineFunctionLibrary::RequestExit(const UObject* WorldContextObject, bool force)
{
UWorld* World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject);
if (!World)
{
return;
}
if (GIsEditor)
{
#if WITH_EDITOR
GEditor->RequestEndPlayMap();
#endif
}
else
{
FPlatformMisc::RequestExit(force);
}
}
FString UEZOnlineFunctionLibrary::GetWorldAddress(const UObject* WorldContextObject)
{
UWorld* World = GEngine->GetWorldFromContextObjectChecked(WorldContextObject);
if (!World)
{
return TEXT("");
}
UGameInstance* pGameInstance = World->GetGameInstance();
if (pGameInstance)
{
FWorldContext* pWorldContext = pGameInstance->GetWorldContext();
if (pWorldContext->LastURL.Valid)
{
//return pWorldContext->LastURL.Port;
}
}
bool bCanBindAll = false;
TSharedPtr<class FInternetAddr> HostAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->GetLocalHostAddr(*GLog, bCanBindAll);
if (HostAddr->IsValid())
{
return *HostAddr->ToString(false);
}
return TEXT("");
}
|
; A145068: Zero followed by partial sums of A059100, starting at n=1.
; 0,3,9,20,38,65,103,154,220,303,405,528,674,845,1043,1270,1528,1819,2145,2508,2910,3353,3839,4370,4948,5575,6253,6984,7770,8613,9515,10478,11504,12595,13753,14980,16278,17649,19095,20618,22220,23903,25669
mov $2,2
lpb $0
add $2,$0
sub $0,1
add $1,$2
lpe
mov $0,$1
|
// seed 8
lbi r0, 128 // icount 0
slbi r0, 0 // icount 1
lbi r1, 128 // icount 2
slbi r1, 0 // icount 3
lbi r2, 128 // icount 4
slbi r2, 0 // icount 5
lbi r3, 128 // icount 6
slbi r3, 0 // icount 7
lbi r4, 128 // icount 8
slbi r4, 0 // icount 9
lbi r5, 128 // icount 10
slbi r5, 0 // icount 11
lbi r6, 128 // icount 12
slbi r6, 0 // icount 13
lbi r7, 128 // icount 14
nop // to align meminst icount 15
slbi r7, 0 // icount 16
nop // to align meminst icount 17
stu r4, r1, -16 // icount 18
nop // to align meminst icount 19
st r6, r0, 14 // icount 20
nop // to align meminst icount 21
ld r3, r1, 10 // icount 22
nop // to align meminst icount 23
ld r2, r1, 6 // icount 24
nop // to align meminst icount 25
ld r5, r0, -4 // icount 26
nop // to align meminst icount 27
stu r5, r0, -6 // icount 28
nop // to align meminst icount 29
st r3, r0, 14 // icount 30
nop // to align meminst icount 31
st r2, r0, 10 // icount 32
nop // to align meminst icount 33
ld r5, r1, -10 // icount 34
nop // to align meminst icount 35
stu r5, r0, 2 // icount 36
stu r5, r0, -14 // icount 37
lbi r2, 0 // icount 38
lbi r3, 0 // icount 39
nop // to align branch icount 40
bltz r1, 16 // icount 41
xor r3, r1, r6 // icount 42
xor r7, r3, r5 // icount 43
subi r3, r4, 11 // icount 44
andni r5, r3, 0 // icount 45
andn r5, r4, r5 // icount 46
srli r5, r5, 4 // icount 47
andni r0, r0, 1 // icount 48
st r3, r0, 6 // icount 49
xori r6, r7, 7 // icount 50
addi r3, r3, 11 // icount 51
sle r2, r7, r5 // icount 52
sub r5, r7, r0 // icount 53
subi r7, r3, 4 // icount 54
nop // to align meminst icount 55
andni r7, r7, 1 // icount 56
st r6, r7, 12 // icount 57
srli r3, r5, 10 // icount 58
xor r6, r5, r4 // icount 59
xor r2, r5, r3 // icount 60
nop // to align meminst icount 61
ld r2, r1, 6 // icount 62
nop // to align meminst icount 63
ld r2, r1, 6 // icount 64
nop // to align meminst icount 65
ld r6, r0, -12 // icount 66
nop // to align meminst icount 67
stu r5, r1, -2 // icount 68
nop // to align meminst icount 69
ld r4, r0, 8 // icount 70
nop // to align meminst icount 71
ld r6, r0, 10 // icount 72
nop // to align meminst icount 73
ld r5, r1, 6 // icount 74
nop // to align meminst icount 75
stu r2, r1, 8 // icount 76
nop // to align meminst icount 77
ld r2, r0, -12 // icount 78
nop // to align meminst icount 79
stu r3, r1, 6 // icount 80
stu r6, r1, 14 // icount 81
slt r5, r4, r5 // icount 82
nop // to align meminst icount 83
ld r4, r1, -4 // icount 84
nop // to align meminst icount 85
st r3, r1, -12 // icount 86
nop // to align meminst icount 87
ld r5, r0, 8 // icount 88
nop // to align meminst icount 89
st r3, r0, 0 // icount 90
nop // to align meminst icount 91
ld r3, r1, 12 // icount 92
nop // to align meminst icount 93
ld r6, r1, -10 // icount 94
nop // to align meminst icount 95
ld r4, r1, 4 // icount 96
nop // to align meminst icount 97
stu r2, r0, 2 // icount 98
nop // to align meminst icount 99
ld r5, r1, -12 // icount 100
nop // to align meminst icount 101
stu r5, r1, 10 // icount 102
nop // to align meminst icount 103
st r6, r1, 4 // icount 104
nop // to align meminst icount 105
ld r6, r0, 14 // icount 106
nop // to align meminst icount 107
st r5, r1, -2 // icount 108
nop // to align meminst icount 109
ld r4, r0, -4 // icount 110
nop // to align meminst icount 111
ld r6, r0, -8 // icount 112
nop // to align meminst icount 113
ld r5, r1, -6 // icount 114
nop // to align meminst icount 115
st r6, r1, 4 // icount 116
nop // to align meminst icount 117
ld r3, r1, -8 // icount 118
nop // to align meminst icount 119
st r6, r1, 0 // icount 120
nop // to align meminst icount 121
stu r5, r0, 4 // icount 122
nop // to align meminst icount 123
ld r4, r1, 8 // icount 124
nop // to align meminst icount 125
ld r4, r0, -16 // icount 126
nop // to align meminst icount 127
ld r2, r1, 6 // icount 128
nop // to align meminst icount 129
ld r4, r1, -6 // icount 130
nop // to align meminst icount 131
ld r4, r0, -8 // icount 132
stu r3, r0, -6 // icount 133
slt r6, r2, r4 // icount 134
nop // to align meminst icount 135
st r3, r1, 0 // icount 136
nop // to align meminst icount 137
ld r4, r1, -2 // icount 138
nop // to align meminst icount 139
ld r5, r0, -16 // icount 140
nop // to align meminst icount 141
ld r2, r0, -14 // icount 142
nop // to align meminst icount 143
ld r2, r1, 12 // icount 144
nop // to align meminst icount 145
stu r2, r1, 14 // icount 146
nop // to align meminst icount 147
stu r3, r1, -4 // icount 148
nop // to align meminst icount 149
st r4, r1, 12 // icount 150
nop // to align meminst icount 151
stu r6, r1, 0 // icount 152
nop // to align meminst icount 153
ld r3, r0, 12 // icount 154
nop // to align meminst icount 155
stu r3, r1, -10 // icount 156
nop // to align meminst icount 157
ld r5, r0, 4 // icount 158
nop // to align meminst icount 159
ld r5, r0, 4 // icount 160
nop // to align meminst icount 161
st r6, r1, 10 // icount 162
nop // to align meminst icount 163
stu r4, r0, -12 // icount 164
nop // to align meminst icount 165
st r5, r0, 6 // icount 166
nop // to align meminst icount 167
ld r6, r0, -14 // icount 168
nop // to align meminst icount 169
stu r6, r0, -2 // icount 170
nop // to align meminst icount 171
ld r3, r1, -14 // icount 172
nop // to align meminst icount 173
ld r2, r1, 8 // icount 174
nop // to align meminst icount 175
st r6, r1, 8 // icount 176
nop // to align meminst icount 177
ld r3, r1, 4 // icount 178
nop // to align meminst icount 179
ld r4, r1, 14 // icount 180
nop // to align meminst icount 181
ld r4, r1, 4 // icount 182
nop // to align meminst icount 183
ld r2, r0, 10 // icount 184
nop // to align meminst icount 185
st r6, r0, 2 // icount 186
nop // to align meminst icount 187
stu r3, r1, 6 // icount 188
nop // to align meminst icount 189
ld r2, r1, 10 // icount 190
nop // to align meminst icount 191
ld r6, r1, -14 // icount 192
nop // to align meminst icount 193
ld r5, r1, -2 // icount 194
nop // to align meminst icount 195
stu r3, r0, -14 // icount 196
nop // to align meminst icount 197
st r6, r1, 0 // icount 198
nop // to align meminst icount 199
st r2, r1, 0 // icount 200
nop // to align meminst icount 201
ld r5, r0, -14 // icount 202
nop // to align meminst icount 203
ld r3, r1, -14 // icount 204
nop // to align meminst icount 205
ld r4, r1, 14 // icount 206
nop // to align meminst icount 207
st r3, r1, -4 // icount 208
nop // to align meminst icount 209
st r5, r1, -14 // icount 210
nop // to align meminst icount 211
st r3, r0, -14 // icount 212
nop // to align meminst icount 213
ld r6, r1, 14 // icount 214
nop // to align meminst icount 215
ld r2, r1, -12 // icount 216
ld r4, r0, 2 // icount 217
rol r3, r4, r1 // icount 218
nop // to align meminst icount 219
stu r6, r1, -14 // icount 220
nop // to align meminst icount 221
st r4, r1, 8 // icount 222
nop // to align meminst icount 223
st r2, r0, -16 // icount 224
nop // to align meminst icount 225
stu r3, r0, -6 // icount 226
nop // to align meminst icount 227
ld r5, r0, -14 // icount 228
nop // to align meminst icount 229
stu r4, r0, 12 // icount 230
nop // to align meminst icount 231
st r3, r1, 6 // icount 232
nop // to align meminst icount 233
ld r3, r1, -8 // icount 234
nop // to align meminst icount 235
ld r4, r0, 14 // icount 236
nop // to align meminst icount 237
stu r2, r0, -8 // icount 238
nop // to align meminst icount 239
stu r6, r1, 2 // icount 240
nop // to align meminst icount 241
ld r2, r0, -8 // icount 242
st r3, r0, 6 // icount 243
lbi r2, 0 // icount 244
lbi r3, 0 // icount 245
nop // to align branch icount 246
beqz r5, 12 // icount 247
seq r5, r0, r7 // icount 248
nop // to align meminst icount 249
andni r4, r4, 1 // icount 250
st r3, r4, 6 // icount 251
lbi r2, 3 // icount 252
andn r2, r0, r6 // icount 253
rol r7, r7, r4 // icount 254
sle r4, r7, r6 // icount 255
slt r4, r0, r6 // icount 256
addi r6, r1, 15 // icount 257
sle r4, r4, r4 // icount 258
andn r6, r2, r1 // icount 259
sub r3, r3, r4 // icount 260
nop // to align meminst icount 261
andni r6, r6, 1 // icount 262
nop // to align meminst icount 263
ld r2, r6, 0 // icount 264
nop // to align meminst icount 265
st r6, r1, -6 // icount 266
nop // to align meminst icount 267
st r3, r0, 10 // icount 268
nop // to align meminst icount 269
st r2, r1, 2 // icount 270
nop // to align meminst icount 271
st r3, r1, -2 // icount 272
nop // to align meminst icount 273
st r2, r1, -6 // icount 274
nop // to align meminst icount 275
st r5, r0, 8 // icount 276
nop // to align meminst icount 277
st r5, r1, -16 // icount 278
nop // to align meminst icount 279
ld r4, r0, -4 // icount 280
nop // to align meminst icount 281
ld r5, r1, 0 // icount 282
nop // to align meminst icount 283
ld r5, r0, -14 // icount 284
nop // to align meminst icount 285
ld r5, r0, -8 // icount 286
nop // to align meminst icount 287
stu r4, r0, -2 // icount 288
nop // to align meminst icount 289
st r4, r1, -14 // icount 290
nop // to align meminst icount 291
stu r5, r0, -8 // icount 292
nop // to align meminst icount 293
ld r4, r1, 6 // icount 294
nop // to align meminst icount 295
stu r5, r1, -8 // icount 296
nop // to align meminst icount 297
stu r2, r0, -10 // icount 298
nop // to align meminst icount 299
ld r4, r1, 6 // icount 300
nop // to align meminst icount 301
ld r4, r1, -14 // icount 302
nop // to align meminst icount 303
st r6, r1, 2 // icount 304
nop // to align meminst icount 305
ld r2, r0, 2 // icount 306
nop // to align meminst icount 307
stu r5, r1, 2 // icount 308
nop // to align meminst icount 309
stu r4, r0, -16 // icount 310
nop // to align meminst icount 311
ld r6, r0, 2 // icount 312
nop // to align meminst icount 313
ld r3, r0, 10 // icount 314
nop // to align meminst icount 315
ld r4, r1, 10 // icount 316
nop // to align meminst icount 317
ld r4, r0, 14 // icount 318
nop // to align meminst icount 319
stu r6, r1, 4 // icount 320
nop // to align meminst icount 321
stu r3, r1, -16 // icount 322
nop // to align meminst icount 323
stu r3, r1, 12 // icount 324
nop // to align meminst icount 325
ld r4, r1, 8 // icount 326
nop // to align meminst icount 327
stu r5, r1, -6 // icount 328
nop // to align meminst icount 329
stu r2, r1, -12 // icount 330
nop // to align meminst icount 331
st r3, r1, -12 // icount 332
nop // to align meminst icount 333
ld r2, r0, 6 // icount 334
nop // to align meminst icount 335
st r3, r0, -4 // icount 336
nop // to align meminst icount 337
ld r6, r1, -16 // icount 338
nop // to align meminst icount 339
stu r4, r1, -14 // icount 340
nop // to align meminst icount 341
ld r6, r1, -12 // icount 342
nop // to align meminst icount 343
ld r5, r0, -4 // icount 344
nop // to align meminst icount 345
stu r5, r1, 8 // icount 346
nop // to align meminst icount 347
ld r2, r1, -8 // icount 348
nop // to align meminst icount 349
st r3, r1, -6 // icount 350
nop // to align meminst icount 351
ld r6, r0, -16 // icount 352
nop // to align meminst icount 353
ld r2, r0, 14 // icount 354
nop // to align meminst icount 355
ld r6, r0, -6 // icount 356
nop // to align meminst icount 357
stu r4, r0, -12 // icount 358
nop // to align meminst icount 359
ld r3, r1, 4 // icount 360
nop // to align meminst icount 361
ld r4, r0, -6 // icount 362
nop // to align meminst icount 363
st r2, r1, -4 // icount 364
nop // to align meminst icount 365
ld r2, r1, 12 // icount 366
nop // to align meminst icount 367
st r2, r1, -4 // icount 368
nop // to align meminst icount 369
ld r3, r1, -8 // icount 370
nop // to align meminst icount 371
ld r2, r0, 14 // icount 372
nop // to align meminst icount 373
stu r4, r0, -10 // icount 374
nop // to align meminst icount 375
ld r3, r0, -6 // icount 376
nop // to align meminst icount 377
ld r6, r1, 10 // icount 378
nop // to align meminst icount 379
stu r6, r1, 6 // icount 380
nop // to align meminst icount 381
ld r6, r0, -4 // icount 382
stu r5, r1, 10 // icount 383
addi r0, r0, -4 // change base addr // icount 384
nop // to align meminst icount 385
ld r4, r0, 12 // icount 386
nop // to align meminst icount 387
st r4, r1, 6 // icount 388
nop // to align meminst icount 389
st r6, r1, -14 // icount 390
nop // to align meminst icount 391
ld r6, r1, 10 // icount 392
nop // to align meminst icount 393
ld r4, r1, -6 // icount 394
nop // to align meminst icount 395
st r5, r1, 6 // icount 396
nop // to align meminst icount 397
stu r6, r1, 4 // icount 398
nop // to align meminst icount 399
ld r2, r0, -12 // icount 400
nop // to align meminst icount 401
st r2, r1, -14 // icount 402
nop // to align meminst icount 403
ld r5, r0, -8 // icount 404
nop // to align meminst icount 405
st r5, r1, -4 // icount 406
nop // to align meminst icount 407
st r5, r0, -6 // icount 408
nop // to align meminst icount 409
ld r6, r0, -4 // icount 410
nop // to align meminst icount 411
ld r4, r1, -16 // icount 412
nop // to align meminst icount 413
ld r6, r0, 0 // icount 414
nop // to align meminst icount 415
st r3, r0, 10 // icount 416
nop // to align meminst icount 417
ld r5, r0, 0 // icount 418
nop // to align meminst icount 419
stu r5, r1, -16 // icount 420
nop // to align meminst icount 421
ld r2, r1, -14 // icount 422
nop // to align meminst icount 423
st r4, r0, -10 // icount 424
nop // to align meminst icount 425
ld r6, r1, -10 // icount 426
nop // to align meminst icount 427
st r3, r1, -6 // icount 428
nop // to align meminst icount 429
ld r6, r1, 10 // icount 430
nop // to align meminst icount 431
stu r3, r0, -6 // icount 432
nop // to align meminst icount 433
st r2, r0, 14 // icount 434
nop // to align meminst icount 435
st r3, r0, -6 // icount 436
nop // to align meminst icount 437
stu r3, r1, -10 // icount 438
nop // to align meminst icount 439
st r6, r0, -16 // icount 440
nop // to align meminst icount 441
ld r2, r0, -16 // icount 442
nop // to align meminst icount 443
ld r3, r1, 10 // icount 444
nop // to align meminst icount 445
st r3, r0, 6 // icount 446
nop // to align meminst icount 447
stu r4, r1, -6 // icount 448
nop // to align meminst icount 449
stu r4, r1, -6 // icount 450
nop // to align meminst icount 451
stu r3, r1, 8 // icount 452
nop // to align meminst icount 453
stu r4, r1, 0 // icount 454
nop // to align meminst icount 455
ld r6, r0, 0 // icount 456
nop // to align meminst icount 457
stu r4, r0, -4 // icount 458
nop // to align meminst icount 459
st r3, r1, 8 // icount 460
nop // to align meminst icount 461
st r5, r1, 2 // icount 462
nop // to align meminst icount 463
ld r6, r1, -2 // icount 464
nop // to align meminst icount 465
ld r4, r0, 4 // icount 466
nop // to align meminst icount 467
ld r4, r0, -4 // icount 468
nop // to align meminst icount 469
stu r6, r1, -10 // icount 470
nop // to align meminst icount 471
ld r6, r1, 4 // icount 472
nop // to align meminst icount 473
stu r5, r1, -14 // icount 474
nop // to align meminst icount 475
stu r3, r1, 0 // icount 476
nop // to align meminst icount 477
stu r4, r1, -6 // icount 478
nop // to align meminst icount 479
ld r4, r1, -12 // icount 480
nop // to align meminst icount 481
ld r5, r1, 10 // icount 482
nop // to align meminst icount 483
stu r4, r0, -6 // icount 484
nop // to align meminst icount 485
st r5, r0, -2 // icount 486
nop // to align meminst icount 487
st r2, r1, -10 // icount 488
nop // to align meminst icount 489
ld r2, r0, 0 // icount 490
nop // to align meminst icount 491
ld r4, r0, -12 // icount 492
nop // to align meminst icount 493
ld r6, r0, -10 // icount 494
nop // to align meminst icount 495
st r3, r1, -6 // icount 496
nop // to align meminst icount 497
ld r4, r0, 14 // icount 498
nop // to align meminst icount 499
ld r3, r0, -4 // icount 500
nop // to align meminst icount 501
ld r6, r1, -12 // icount 502
nop // to align meminst icount 503
ld r5, r0, -6 // icount 504
nop // to align meminst icount 505
ld r4, r0, -14 // icount 506
nop // to align meminst icount 507
st r3, r0, -8 // icount 508
nop // to align meminst icount 509
st r4, r0, -8 // icount 510
nop // to align meminst icount 511
st r6, r0, -16 // icount 512
nop // to align meminst icount 513
ld r6, r0, 0 // icount 514
nop // to align meminst icount 515
stu r2, r0, -12 // icount 516
nop // to align meminst icount 517
st r5, r1, 6 // icount 518
nop // to align meminst icount 519
stu r5, r0, -2 // icount 520
nop // to align meminst icount 521
stu r6, r0, -10 // icount 522
nop // to align meminst icount 523
stu r5, r0, 0 // icount 524
nop // to align meminst icount 525
ld r4, r0, 10 // icount 526
nop // to align meminst icount 527
ld r2, r1, -16 // icount 528
nop // to align meminst icount 529
ld r3, r0, -12 // icount 530
nop // to align meminst icount 531
stu r4, r0, 14 // icount 532
nop // to align meminst icount 533
ld r5, r0, -6 // icount 534
nop // to align meminst icount 535
stu r2, r1, -6 // icount 536
nop // to align meminst icount 537
st r4, r0, 6 // icount 538
nop // to align meminst icount 539
ld r5, r0, 2 // icount 540
nop // to align meminst icount 541
ld r2, r1, -12 // icount 542
nop // to align meminst icount 543
stu r3, r0, 2 // icount 544
nop // to align meminst icount 545
st r6, r1, 6 // icount 546
nop // to align meminst icount 547
ld r3, r1, -14 // icount 548
nop // to align meminst icount 549
ld r4, r1, 2 // icount 550
nop // to align meminst icount 551
ld r4, r1, 6 // icount 552
nop // to align meminst icount 553
st r2, r0, -14 // icount 554
nop // to align meminst icount 555
stu r2, r1, 6 // icount 556
nop // to align meminst icount 557
stu r5, r1, -6 // icount 558
nop // to align meminst icount 559
st r5, r0, 12 // icount 560
nop // to align meminst icount 561
ld r3, r1, -14 // icount 562
nop // to align meminst icount 563
stu r2, r1, -8 // icount 564
st r5, r1, -10 // icount 565
addi r0, r0, 0 // change base addr // icount 566
nop // to align meminst icount 567
ld r3, r0, 14 // icount 568
nop // to align meminst icount 569
st r2, r0, 10 // icount 570
nop // to align meminst icount 571
ld r5, r0, 6 // icount 572
nop // to align meminst icount 573
stu r4, r1, -16 // icount 574
nop // to align meminst icount 575
ld r2, r1, -2 // icount 576
nop // to align meminst icount 577
stu r4, r1, -6 // icount 578
nop // to align meminst icount 579
stu r5, r0, 10 // icount 580
nop // to align meminst icount 581
ld r4, r0, -6 // icount 582
nop // to align meminst icount 583
st r4, r1, -16 // icount 584
nop // to align meminst icount 585
stu r5, r0, -2 // icount 586
nop // to align meminst icount 587
ld r6, r0, 14 // icount 588
nop // to align meminst icount 589
st r4, r0, 0 // icount 590
nop // to align meminst icount 591
st r5, r1, -12 // icount 592
st r5, r1, -14 // icount 593
addi r0, r0, 8 // change base addr // icount 594
nop // to align meminst icount 595
ld r5, r0, -12 // icount 596
nop // to align meminst icount 597
ld r4, r1, 10 // icount 598
nop // to align meminst icount 599
st r4, r1, -6 // icount 600
nop // to align meminst icount 601
ld r2, r1, 4 // icount 602
nop // to align meminst icount 603
ld r5, r0, 8 // icount 604
nop // to align meminst icount 605
st r3, r1, -16 // icount 606
nop // to align meminst icount 607
ld r3, r0, -4 // icount 608
nop // to align meminst icount 609
st r4, r1, -2 // icount 610
nop // to align meminst icount 611
ld r2, r0, 12 // icount 612
nop // to align meminst icount 613
st r5, r1, 4 // icount 614
nop // to align meminst icount 615
st r3, r1, 2 // icount 616
nop // to align meminst icount 617
st r6, r1, 14 // icount 618
nop // to align meminst icount 619
st r6, r1, -2 // icount 620
nop // to align meminst icount 621
ld r6, r1, -10 // icount 622
nop // to align meminst icount 623
ld r6, r1, 2 // icount 624
nop // to align meminst icount 625
st r2, r1, -16 // icount 626
nop // to align meminst icount 627
ld r3, r1, 8 // icount 628
nop // to align meminst icount 629
stu r2, r0, 12 // icount 630
nop // to align meminst icount 631
stu r4, r1, 8 // icount 632
nop // to align meminst icount 633
ld r2, r0, 0 // icount 634
nop // to align meminst icount 635
st r5, r0, -10 // icount 636
nop // to align meminst icount 637
stu r3, r0, -16 // icount 638
nop // to align meminst icount 639
st r5, r0, -10 // icount 640
nop // to align meminst icount 641
ld r3, r0, 14 // icount 642
nop // to align meminst icount 643
ld r6, r1, 4 // icount 644
nop // to align meminst icount 645
ld r5, r0, 4 // icount 646
nop // to align meminst icount 647
st r4, r0, -8 // icount 648
nop // to align meminst icount 649
ld r2, r1, -14 // icount 650
nop // to align meminst icount 651
ld r3, r0, -6 // icount 652
nop // to align meminst icount 653
st r5, r1, -6 // icount 654
nop // to align meminst icount 655
st r4, r1, 4 // icount 656
nop // to align meminst icount 657
ld r2, r0, -12 // icount 658
nop // to align meminst icount 659
stu r6, r0, 14 // icount 660
nop // to align meminst icount 661
ld r4, r0, -2 // icount 662
nop // to align meminst icount 663
stu r3, r1, -16 // icount 664
nop // to align meminst icount 665
stu r6, r1, 8 // icount 666
nop // to align meminst icount 667
ld r2, r0, -16 // icount 668
nop // to align meminst icount 669
ld r3, r0, -6 // icount 670
nop // to align meminst icount 671
stu r2, r1, 12 // icount 672
st r3, r1, 0 // icount 673
andn r7, r1, r0 // icount 674
nop // to align meminst icount 675
st r5, r0, 6 // icount 676
nop // to align meminst icount 677
ld r3, r0, -16 // icount 678
nop // to align meminst icount 679
ld r4, r0, 12 // icount 680
nop // to align meminst icount 681
ld r4, r1, -14 // icount 682
nop // to align meminst icount 683
ld r3, r0, -10 // icount 684
nop // to align meminst icount 685
stu r4, r1, -16 // icount 686
nop // to align meminst icount 687
stu r6, r0, -6 // icount 688
nop // to align meminst icount 689
ld r6, r1, 14 // icount 690
nop // to align meminst icount 691
ld r6, r0, -14 // icount 692
st r2, r0, -16 // icount 693
addi r1, r1, -4 // change base addr // icount 694
nop // to align meminst icount 695
st r6, r1, -10 // icount 696
nop // to align meminst icount 697
ld r2, r0, -2 // icount 698
nop // to align meminst icount 699
st r3, r0, 6 // icount 700
nop // to align meminst icount 701
ld r2, r0, 10 // icount 702
nop // to align meminst icount 703
st r6, r0, 12 // icount 704
nop // to align meminst icount 705
st r2, r1, 14 // icount 706
nop // to align meminst icount 707
ld r3, r1, -6 // icount 708
nop // to align meminst icount 709
ld r3, r0, 12 // icount 710
nop // to align meminst icount 711
st r3, r0, 10 // icount 712
nop // to align meminst icount 713
ld r6, r1, -6 // icount 714
nop // to align meminst icount 715
stu r4, r1, 8 // icount 716
nop // to align meminst icount 717
stu r5, r0, 8 // icount 718
nop // to align meminst icount 719
ld r5, r1, 2 // icount 720
nop // to align meminst icount 721
ld r6, r0, 4 // icount 722
nop // to align meminst icount 723
stu r5, r1, -10 // icount 724
nop // to align meminst icount 725
ld r4, r1, 6 // icount 726
nop // to align meminst icount 727
st r6, r0, 14 // icount 728
nop // to align meminst icount 729
ld r3, r0, 0 // icount 730
nop // to align meminst icount 731
ld r5, r0, 6 // icount 732
nop // to align meminst icount 733
ld r2, r1, -2 // icount 734
nop // to align meminst icount 735
ld r5, r1, 4 // icount 736
nop // to align meminst icount 737
ld r5, r1, 14 // icount 738
nop // to align meminst icount 739
ld r6, r0, 12 // icount 740
nop // to align meminst icount 741
ld r6, r1, 2 // icount 742
nop // to align meminst icount 743
ld r5, r0, 12 // icount 744
nop // to align meminst icount 745
ld r4, r1, 14 // icount 746
nop // to align meminst icount 747
ld r3, r1, 14 // icount 748
nop // to align meminst icount 749
stu r3, r1, 10 // icount 750
nop // to align meminst icount 751
stu r4, r0, 0 // icount 752
nop // to align meminst icount 753
ld r4, r0, 8 // icount 754
nop // to align meminst icount 755
stu r3, r0, -6 // icount 756
nop // to align meminst icount 757
ld r5, r0, 8 // icount 758
stu r3, r1, 8 // icount 759
lbi r2, 0 // icount 760
lbi r6, 0 // icount 761
nop // to align branch icount 762
bnez r7, 8 // icount 763
xori r5, r1, 13 // icount 764
lbi r5, 12 // icount 765
subi r5, r0, 5 // icount 766
nop // to align meminst icount 767
andni r0, r0, 1 // icount 768
st r4, r0, 0 // icount 769
sll r3, r0, r7 // icount 770
sub r6, r3, r1 // icount 771
subi r6, r5, 3 // icount 772
nop // to align meminst icount 773
andni r1, r1, 1 // icount 774
nop // to align meminst icount 775
stu r3, r1, 14 // icount 776
st r5, r0, 12 // icount 777
addi r0, r0, -2 // change base addr // icount 778
nop // to align meminst icount 779
stu r2, r1, -4 // icount 780
nop // to align meminst icount 781
ld r6, r0, 2 // icount 782
nop // to align meminst icount 783
stu r3, r0, 8 // icount 784
nop // to align meminst icount 785
st r5, r0, 14 // icount 786
nop // to align meminst icount 787
stu r4, r0, 14 // icount 788
nop // to align meminst icount 789
ld r4, r0, 6 // icount 790
nop // to align meminst icount 791
ld r2, r1, -14 // icount 792
nop // to align meminst icount 793
ld r2, r1, 14 // icount 794
nop // to align meminst icount 795
stu r4, r0, -16 // icount 796
nop // to align meminst icount 797
ld r3, r0, -2 // icount 798
nop // to align meminst icount 799
ld r3, r1, 12 // icount 800
nop // to align meminst icount 801
stu r6, r0, -4 // icount 802
nop // to align meminst icount 803
stu r4, r1, -12 // icount 804
nop // to align meminst icount 805
st r3, r0, 10 // icount 806
nop // to align meminst icount 807
ld r3, r1, 6 // icount 808
nop // to align meminst icount 809
ld r4, r1, 12 // icount 810
nop // to align meminst icount 811
ld r2, r1, 6 // icount 812
nop // to align meminst icount 813
stu r5, r1, 8 // icount 814
nop // to align meminst icount 815
ld r2, r0, -10 // icount 816
nop // to align meminst icount 817
st r6, r1, -12 // icount 818
nop // to align meminst icount 819
ld r5, r1, -16 // icount 820
nop // to align meminst icount 821
stu r3, r0, 4 // icount 822
nop // to align meminst icount 823
st r4, r0, -6 // icount 824
nop // to align meminst icount 825
ld r2, r1, -10 // icount 826
nop // to align meminst icount 827
ld r4, r1, -14 // icount 828
nop // to align meminst icount 829
ld r3, r1, -6 // icount 830
nop // to align meminst icount 831
ld r6, r1, 4 // icount 832
nop // to align meminst icount 833
st r5, r1, 6 // icount 834
nop // to align meminst icount 835
ld r2, r1, -14 // icount 836
nop // to align meminst icount 837
ld r3, r0, 6 // icount 838
nop // to align meminst icount 839
stu r4, r0, 12 // icount 840
nop // to align meminst icount 841
ld r6, r1, -16 // icount 842
nop // to align meminst icount 843
ld r3, r1, -8 // icount 844
nop // to align meminst icount 845
st r2, r0, 6 // icount 846
nop // to align meminst icount 847
ld r3, r0, -16 // icount 848
nop // to align meminst icount 849
st r4, r1, 14 // icount 850
nop // to align meminst icount 851
ld r5, r1, 12 // icount 852
nop // to align meminst icount 853
ld r6, r0, 10 // icount 854
nop // to align meminst icount 855
stu r5, r1, 0 // icount 856
nop // to align meminst icount 857
stu r6, r1, -2 // icount 858
ld r4, r0, 8 // icount 859
ror r7, r5, r1 // icount 860
nop // to align meminst icount 861
st r2, r0, 2 // icount 862
nop // to align meminst icount 863
ld r2, r1, 14 // icount 864
nop // to align meminst icount 865
ld r3, r1, -14 // icount 866
nop // to align meminst icount 867
st r6, r0, -10 // icount 868
nop // to align meminst icount 869
ld r4, r0, -16 // icount 870
nop // to align meminst icount 871
ld r6, r1, 8 // icount 872
nop // to align meminst icount 873
ld r5, r0, 12 // icount 874
nop // to align meminst icount 875
ld r5, r0, -16 // icount 876
nop // to align meminst icount 877
stu r6, r0, -2 // icount 878
nop // to align meminst icount 879
ld r4, r1, -4 // icount 880
nop // to align meminst icount 881
st r5, r1, 4 // icount 882
nop // to align meminst icount 883
stu r4, r0, 0 // icount 884
nop // to align meminst icount 885
ld r4, r1, 6 // icount 886
nop // to align meminst icount 887
stu r4, r0, 4 // icount 888
nop // to align meminst icount 889
stu r5, r1, -10 // icount 890
nop // to align meminst icount 891
ld r5, r1, 6 // icount 892
nop // to align meminst icount 893
stu r3, r0, 2 // icount 894
nop // to align meminst icount 895
st r3, r0, -12 // icount 896
nop // to align meminst icount 897
st r2, r0, -2 // icount 898
nop // to align meminst icount 899
st r2, r0, 10 // icount 900
stu r4, r0, 14 // icount 901
roli r4, r5, 6 // icount 902
nop // to align meminst icount 903
st r6, r0, 0 // icount 904
nop // to align meminst icount 905
st r5, r0, -6 // icount 906
st r4, r0, -12 // icount 907
xori r2, r6, 7 // icount 908
lbi r3, 0 // icount 909
lbi r2, 0 // icount 910
beqz r0, 16 // icount 911
slli r7, r4, 12 // icount 912
sub r6, r0, r7 // icount 913
srli r3, r7, 9 // icount 914
add r5, r7, r1 // icount 915
seq r2, r1, r1 // icount 916
andni r3, r1, 13 // icount 917
xor r3, r1, r0 // icount 918
seq r6, r5, r3 // icount 919
ror r7, r0, r0 // icount 920
roli r4, r5, 12 // icount 921
rori r7, r2, 9 // icount 922
addi r3, r5, 2 // icount 923
rori r2, r7, 14 // icount 924
nop // to align meminst icount 925
andni r1, r1, 1 // icount 926
st r5, r1, 10 // icount 927
seq r2, r3, r5 // icount 928
nop // to align meminst icount 929
slt r4, r0, r4 // icount 930
nop // to align meminst icount 931
st r6, r0, 14 // icount 932
nop // to align meminst icount 933
st r3, r1, -8 // icount 934
nop // to align meminst icount 935
st r4, r1, -16 // icount 936
nop // to align meminst icount 937
ld r2, r1, 6 // icount 938
nop // to align meminst icount 939
stu r2, r1, 0 // icount 940
nop // to align meminst icount 941
ld r4, r0, -4 // icount 942
nop // to align meminst icount 943
st r4, r0, -8 // icount 944
nop // to align meminst icount 945
stu r5, r1, 4 // icount 946
nop // to align meminst icount 947
ld r3, r0, 0 // icount 948
nop // to align meminst icount 949
stu r6, r1, -2 // icount 950
nop // to align meminst icount 951
ld r4, r0, 6 // icount 952
nop // to align meminst icount 953
ld r2, r0, 10 // icount 954
nop // to align meminst icount 955
stu r2, r0, 0 // icount 956
nop // to align meminst icount 957
st r2, r1, 6 // icount 958
nop // to align meminst icount 959
st r6, r0, -16 // icount 960
nop // to align meminst icount 961
stu r3, r1, -10 // icount 962
nop // to align meminst icount 963
st r5, r1, 10 // icount 964
nop // to align meminst icount 965
ld r3, r1, 10 // icount 966
nop // to align meminst icount 967
st r2, r1, 4 // icount 968
nop // to align meminst icount 969
stu r6, r0, 0 // icount 970
nop // to align meminst icount 971
stu r5, r1, -6 // icount 972
stu r4, r1, -12 // icount 973
ror r3, r4, r5 // icount 974
nop // to align meminst icount 975
ld r6, r1, -16 // icount 976
nop // to align meminst icount 977
st r3, r0, -12 // icount 978
nop // to align meminst icount 979
st r5, r0, -10 // icount 980
nop // to align meminst icount 981
ld r4, r1, 14 // icount 982
nop // to align meminst icount 983
ld r3, r0, 0 // icount 984
nop // to align meminst icount 985
st r5, r1, -12 // icount 986
nop // to align meminst icount 987
st r5, r0, 4 // icount 988
nop // to align meminst icount 989
ld r6, r1, 2 // icount 990
nop // to align meminst icount 991
ld r3, r0, 0 // icount 992
nop // to align meminst icount 993
ld r2, r0, -12 // icount 994
nop // to align meminst icount 995
ld r4, r0, 0 // icount 996
nop // to align meminst icount 997
ld r2, r1, 14 // icount 998
st r2, r1, -2 // icount 999
addi r1, r1, 8 // change base addr // icount 1000
nop // to align meminst icount 1001
ld r2, r1, 4 // icount 1002
nop // to align meminst icount 1003
ld r6, r1, 2 // icount 1004
nop // to align meminst icount 1005
ld r5, r1, 0 // icount 1006
nop // to align meminst icount 1007
stu r4, r1, -8 // icount 1008
nop // to align meminst icount 1009
stu r5, r1, -4 // icount 1010
nop // to align meminst icount 1011
ld r6, r1, 10 // icount 1012
nop // to align meminst icount 1013
st r4, r0, 12 // icount 1014
nop // to align meminst icount 1015
ld r4, r0, -8 // icount 1016
nop // to align meminst icount 1017
ld r6, r1, 10 // icount 1018
st r3, r1, 6 // icount 1019
lbi r6, 0 // icount 1020
lbi r2, 0 // icount 1021
nop // to align branch icount 1022
bnez r4, 32 // icount 1023
andni r0, r0, 1 // icount 1024
ld r6, r0, 10 // icount 1025
addi r5, r3, 11 // icount 1026
addi r2, r6, 5 // icount 1027
addi r2, r7, 0 // icount 1028
add r3, r7, r1 // icount 1029
andni r6, r6, 1 // icount 1030
stu r5, r6, 2 // icount 1031
xor r4, r2, r4 // icount 1032
slbi r3, 15 // icount 1033
slli r4, r3, 7 // icount 1034
sub r7, r7, r3 // icount 1035
xori r5, r2, 11 // icount 1036
slli r7, r3, 6 // icount 1037
add r4, r0, r0 // icount 1038
srl r3, r1, r0 // icount 1039
andni r2, r1, 1 // icount 1040
andni r4, r1, 9 // icount 1041
addi r3, r5, 12 // icount 1042
andn r2, r7, r2 // icount 1043
roli r3, r5, 3 // icount 1044
nop // to align meminst icount 1045
andni r4, r4, 1 // icount 1046
stu r5, r4, 0 // icount 1047
slli r4, r2, 1 // icount 1048
slt r3, r0, r5 // icount 1049
andni r5, r5, 1 // icount 1050
ld r6, r5, 0 // icount 1051
slbi r2, 10 // icount 1052
srl r5, r0, r2 // icount 1053
subi r6, r7, 14 // icount 1054
slbi r3, 13 // icount 1055
slbi r7, 8 // icount 1056
srl r7, r7, r7 // icount 1057
rol r7, r0, r6 // icount 1058
sub r4, r5, r1 // icount 1059
andni r3, r3, 1 // icount 1060
nop // to align meminst icount 1061
st r3, r3, 10 // icount 1062
nop // to align meminst icount 1063
st r5, r1, 10 // icount 1064
nop // to align meminst icount 1065
stu r2, r0, 8 // icount 1066
nop // to align meminst icount 1067
st r5, r1, 0 // icount 1068
nop // to align meminst icount 1069
ld r3, r0, -6 // icount 1070
nop // to align meminst icount 1071
ld r6, r0, 8 // icount 1072
nop // to align meminst icount 1073
ld r3, r1, -14 // icount 1074
nop // to align meminst icount 1075
stu r2, r0, 10 // icount 1076
nop // to align meminst icount 1077
st r2, r0, 4 // icount 1078
nop // to align meminst icount 1079
stu r4, r0, 4 // icount 1080
nop // to align meminst icount 1081
ld r3, r0, -10 // icount 1082
nop // to align meminst icount 1083
st r3, r0, 12 // icount 1084
nop // to align meminst icount 1085
ld r6, r1, -4 // icount 1086
nop // to align meminst icount 1087
st r4, r0, -4 // icount 1088
nop // to align meminst icount 1089
ld r6, r1, -8 // icount 1090
nop // to align meminst icount 1091
st r6, r1, 12 // icount 1092
nop // to align meminst icount 1093
st r5, r0, 6 // icount 1094
nop // to align meminst icount 1095
ld r6, r0, 0 // icount 1096
nop // to align meminst icount 1097
ld r5, r0, -4 // icount 1098
nop // to align meminst icount 1099
ld r2, r0, 0 // icount 1100
nop // to align meminst icount 1101
st r5, r0, 2 // icount 1102
nop // to align meminst icount 1103
st r2, r1, 6 // icount 1104
nop // to align meminst icount 1105
ld r3, r0, 8 // icount 1106
nop // to align meminst icount 1107
stu r6, r0, -12 // icount 1108
nop // to align meminst icount 1109
ld r5, r0, -2 // icount 1110
nop // to align meminst icount 1111
stu r5, r1, 14 // icount 1112
nop // to align meminst icount 1113
stu r4, r0, 0 // icount 1114
nop // to align meminst icount 1115
st r6, r0, 14 // icount 1116
nop // to align meminst icount 1117
ld r3, r1, -2 // icount 1118
nop // to align meminst icount 1119
ld r3, r0, -14 // icount 1120
st r5, r0, -14 // icount 1121
roli r2, r3, 11 // icount 1122
nop // to align meminst icount 1123
ld r2, r1, 10 // icount 1124
nop // to align meminst icount 1125
st r3, r1, 6 // icount 1126
nop // to align meminst icount 1127
stu r6, r1, 6 // icount 1128
nop // to align meminst icount 1129
ld r5, r0, -6 // icount 1130
nop // to align meminst icount 1131
st r3, r1, -8 // icount 1132
nop // to align meminst icount 1133
ld r2, r0, 14 // icount 1134
nop // to align meminst icount 1135
ld r4, r0, -10 // icount 1136
nop // to align meminst icount 1137
st r2, r1, -2 // icount 1138
nop // to align meminst icount 1139
ld r2, r0, 14 // icount 1140
nop // to align meminst icount 1141
st r6, r0, -2 // icount 1142
nop // to align meminst icount 1143
stu r3, r1, 0 // icount 1144
nop // to align meminst icount 1145
ld r3, r1, -12 // icount 1146
nop // to align meminst icount 1147
ld r4, r0, -6 // icount 1148
nop // to align meminst icount 1149
ld r3, r0, -6 // icount 1150
nop // to align meminst icount 1151
st r3, r1, -6 // icount 1152
nop // to align meminst icount 1153
stu r5, r0, 14 // icount 1154
nop // to align meminst icount 1155
ld r3, r1, -8 // icount 1156
nop // to align meminst icount 1157
ld r6, r0, 6 // icount 1158
nop // to align meminst icount 1159
stu r5, r0, 12 // icount 1160
nop // to align meminst icount 1161
ld r5, r0, -8 // icount 1162
nop // to align meminst icount 1163
st r2, r0, -10 // icount 1164
nop // to align meminst icount 1165
ld r5, r0, -2 // icount 1166
nop // to align meminst icount 1167
st r4, r1, -12 // icount 1168
nop // to align meminst icount 1169
ld r5, r0, -8 // icount 1170
nop // to align meminst icount 1171
ld r5, r1, -12 // icount 1172
nop // to align meminst icount 1173
st r2, r0, 10 // icount 1174
nop // to align meminst icount 1175
ld r3, r0, -8 // icount 1176
nop // to align meminst icount 1177
ld r5, r0, -16 // icount 1178
nop // to align meminst icount 1179
st r2, r0, -2 // icount 1180
nop // to align meminst icount 1181
stu r3, r0, 6 // icount 1182
nop // to align meminst icount 1183
stu r4, r1, -14 // icount 1184
nop // to align meminst icount 1185
st r6, r0, 14 // icount 1186
nop // to align meminst icount 1187
st r2, r0, 0 // icount 1188
nop // to align meminst icount 1189
st r4, r0, 10 // icount 1190
nop // to align meminst icount 1191
st r6, r1, -10 // icount 1192
nop // to align meminst icount 1193
stu r5, r0, -16 // icount 1194
nop // to align meminst icount 1195
st r5, r1, -2 // icount 1196
nop // to align meminst icount 1197
ld r2, r0, -12 // icount 1198
nop // to align meminst icount 1199
stu r4, r1, 0 // icount 1200
nop // to align meminst icount 1201
st r5, r1, -8 // icount 1202
nop // to align meminst icount 1203
ld r4, r0, 2 // icount 1204
nop // to align meminst icount 1205
st r2, r0, -12 // icount 1206
nop // to align meminst icount 1207
stu r3, r0, 12 // icount 1208
nop // to align meminst icount 1209
ld r2, r0, 14 // icount 1210
nop // to align meminst icount 1211
stu r4, r1, -10 // icount 1212
nop // to align meminst icount 1213
st r6, r0, 6 // icount 1214
nop // to align meminst icount 1215
ld r3, r0, -6 // icount 1216
nop // to align meminst icount 1217
ld r6, r1, 12 // icount 1218
nop // to align meminst icount 1219
ld r4, r1, 10 // icount 1220
nop // to align meminst icount 1221
ld r5, r0, 12 // icount 1222
nop // to align meminst icount 1223
ld r4, r1, -10 // icount 1224
nop // to align meminst icount 1225
st r4, r1, -12 // icount 1226
nop // to align meminst icount 1227
ld r4, r1, -10 // icount 1228
nop // to align meminst icount 1229
stu r2, r0, -14 // icount 1230
nop // to align meminst icount 1231
ld r3, r0, 8 // icount 1232
nop // to align meminst icount 1233
ld r4, r0, 0 // icount 1234
nop // to align meminst icount 1235
stu r5, r0, -16 // icount 1236
nop // to align meminst icount 1237
st r3, r1, -8 // icount 1238
nop // to align meminst icount 1239
st r2, r0, 0 // icount 1240
nop // to align meminst icount 1241
stu r6, r0, 10 // icount 1242
nop // to align meminst icount 1243
ld r2, r1, 4 // icount 1244
nop // to align meminst icount 1245
ld r4, r0, 4 // icount 1246
nop // to align meminst icount 1247
st r3, r1, 8 // icount 1248
st r4, r0, 0 // icount 1249
roli r5, r1, 2 // icount 1250
nop // to align meminst icount 1251
stu r3, r0, -8 // icount 1252
nop // to align meminst icount 1253
ld r4, r1, -2 // icount 1254
nop // to align meminst icount 1255
stu r2, r0, -10 // icount 1256
nop // to align meminst icount 1257
stu r6, r1, -6 // icount 1258
nop // to align meminst icount 1259
stu r5, r1, -16 // icount 1260
nop // to align meminst icount 1261
ld r2, r0, 4 // icount 1262
nop // to align meminst icount 1263
stu r4, r0, 8 // icount 1264
nop // to align meminst icount 1265
st r4, r0, -6 // icount 1266
nop // to align meminst icount 1267
ld r6, r1, -16 // icount 1268
ld r4, r1, -4 // icount 1269
slbi r3, 11 // icount 1270
nop // to align meminst icount 1271
st r4, r0, 2 // icount 1272
nop // to align meminst icount 1273
st r2, r0, -14 // icount 1274
nop // to align meminst icount 1275
stu r5, r0, 8 // icount 1276
nop // to align meminst icount 1277
ld r6, r0, 4 // icount 1278
nop // to align meminst icount 1279
ld r5, r0, 12 // icount 1280
nop // to align meminst icount 1281
st r3, r0, 14 // icount 1282
nop // to align meminst icount 1283
ld r3, r0, -8 // icount 1284
nop // to align meminst icount 1285
ld r6, r1, 6 // icount 1286
nop // to align meminst icount 1287
stu r2, r1, -4 // icount 1288
nop // to align meminst icount 1289
stu r3, r0, -4 // icount 1290
nop // to align meminst icount 1291
ld r4, r0, -12 // icount 1292
nop // to align meminst icount 1293
ld r4, r1, -16 // icount 1294
nop // to align meminst icount 1295
ld r5, r0, 4 // icount 1296
nop // to align meminst icount 1297
ld r5, r1, 4 // icount 1298
nop // to align meminst icount 1299
stu r5, r0, 0 // icount 1300
nop // to align meminst icount 1301
ld r6, r0, 4 // icount 1302
nop // to align meminst icount 1303
st r3, r0, 14 // icount 1304
nop // to align meminst icount 1305
ld r3, r1, -10 // icount 1306
nop // to align meminst icount 1307
ld r5, r0, 6 // icount 1308
nop // to align meminst icount 1309
ld r2, r0, 6 // icount 1310
nop // to align meminst icount 1311
ld r4, r0, 0 // icount 1312
nop // to align meminst icount 1313
st r5, r1, 8 // icount 1314
nop // to align meminst icount 1315
ld r6, r0, 4 // icount 1316
nop // to align meminst icount 1317
st r3, r0, -4 // icount 1318
nop // to align meminst icount 1319
ld r4, r0, -2 // icount 1320
nop // to align meminst icount 1321
st r5, r1, -8 // icount 1322
nop // to align meminst icount 1323
ld r6, r0, -10 // icount 1324
nop // to align meminst icount 1325
st r3, r1, -16 // icount 1326
nop // to align meminst icount 1327
ld r4, r1, -2 // icount 1328
nop // to align meminst icount 1329
ld r4, r1, 2 // icount 1330
nop // to align meminst icount 1331
stu r4, r0, -2 // icount 1332
nop // to align meminst icount 1333
st r2, r1, -16 // icount 1334
nop // to align meminst icount 1335
ld r3, r1, 8 // icount 1336
nop // to align meminst icount 1337
ld r4, r1, 14 // icount 1338
nop // to align meminst icount 1339
st r5, r1, -8 // icount 1340
nop // to align meminst icount 1341
ld r3, r1, -8 // icount 1342
nop // to align meminst icount 1343
ld r4, r1, -8 // icount 1344
nop // to align meminst icount 1345
stu r2, r1, -14 // icount 1346
nop // to align meminst icount 1347
stu r6, r1, 2 // icount 1348
nop // to align meminst icount 1349
ld r4, r1, 10 // icount 1350
nop // to align meminst icount 1351
stu r3, r1, -12 // icount 1352
nop // to align meminst icount 1353
stu r6, r0, 12 // icount 1354
nop // to align meminst icount 1355
st r3, r1, -8 // icount 1356
ld r3, r1, -12 // icount 1357
lbi r2, 0 // icount 1358
lbi r2, 0 // icount 1359
nop // to align branch icount 1360
bnez r4, 16 // icount 1361
sll r6, r0, r1 // icount 1362
xor r6, r0, r5 // icount 1363
andni r6, r6, 1 // icount 1364
st r3, r6, 8 // icount 1365
slli r3, r0, 14 // icount 1366
srli r4, r2, 0 // icount 1367
andni r6, r0, 3 // icount 1368
xori r2, r7, 6 // icount 1369
slli r5, r6, 5 // icount 1370
xori r6, r6, 5 // icount 1371
rol r6, r2, r2 // icount 1372
addi r3, r4, 8 // icount 1373
rol r5, r0, r2 // icount 1374
xori r4, r1, 8 // icount 1375
roli r7, r5, 7 // icount 1376
andn r5, r1, r0 // icount 1377
rori r6, r5, 4 // icount 1378
nop // to align meminst icount 1379
st r4, r0, 8 // icount 1380
nop // to align meminst icount 1381
ld r6, r1, 14 // icount 1382
nop // to align meminst icount 1383
ld r5, r0, 12 // icount 1384
nop // to align meminst icount 1385
ld r6, r1, -4 // icount 1386
nop // to align meminst icount 1387
ld r3, r1, 12 // icount 1388
nop // to align meminst icount 1389
st r2, r1, 12 // icount 1390
nop // to align meminst icount 1391
st r5, r1, 8 // icount 1392
stu r6, r0, 6 // icount 1393
andni r4, r4, 1 // icount 1394
nop // to align meminst icount 1395
st r4, r4, 14 // icount 1396
nop // to align meminst icount 1397
stu r2, r1, 2 // icount 1398
nop // to align meminst icount 1399
st r2, r0, 6 // icount 1400
nop // to align meminst icount 1401
ld r3, r1, -16 // icount 1402
nop // to align meminst icount 1403
stu r6, r0, -14 // icount 1404
nop // to align meminst icount 1405
ld r5, r0, 2 // icount 1406
nop // to align meminst icount 1407
ld r5, r0, 0 // icount 1408
nop // to align meminst icount 1409
ld r3, r0, -4 // icount 1410
nop // to align meminst icount 1411
st r3, r0, 12 // icount 1412
nop // to align meminst icount 1413
st r5, r1, 10 // icount 1414
nop // to align meminst icount 1415
stu r5, r1, 0 // icount 1416
nop // to align meminst icount 1417
ld r6, r0, 8 // icount 1418
nop // to align meminst icount 1419
st r5, r0, 12 // icount 1420
nop // to align meminst icount 1421
st r4, r1, -12 // icount 1422
nop // to align meminst icount 1423
ld r2, r0, -2 // icount 1424
nop // to align meminst icount 1425
ld r5, r1, -2 // icount 1426
nop // to align meminst icount 1427
ld r6, r0, 8 // icount 1428
nop // to align meminst icount 1429
ld r2, r0, 12 // icount 1430
nop // to align meminst icount 1431
stu r2, r1, -12 // icount 1432
nop // to align meminst icount 1433
ld r6, r1, 2 // icount 1434
nop // to align meminst icount 1435
st r2, r0, -8 // icount 1436
nop // to align meminst icount 1437
ld r4, r1, 12 // icount 1438
nop // to align meminst icount 1439
st r5, r1, 2 // icount 1440
nop // to align meminst icount 1441
ld r4, r0, -2 // icount 1442
nop // to align meminst icount 1443
st r4, r1, -6 // icount 1444
nop // to align meminst icount 1445
st r6, r1, 14 // icount 1446
nop // to align meminst icount 1447
stu r2, r1, 6 // icount 1448
nop // to align meminst icount 1449
st r2, r1, 12 // icount 1450
nop // to align meminst icount 1451
st r2, r0, -10 // icount 1452
nop // to align meminst icount 1453
ld r3, r0, 8 // icount 1454
nop // to align meminst icount 1455
ld r4, r1, 14 // icount 1456
nop // to align meminst icount 1457
stu r5, r0, 4 // icount 1458
nop // to align meminst icount 1459
st r5, r1, -10 // icount 1460
nop // to align meminst icount 1461
st r2, r0, -4 // icount 1462
nop // to align meminst icount 1463
ld r5, r1, -4 // icount 1464
nop // to align meminst icount 1465
stu r5, r0, 0 // icount 1466
nop // to align meminst icount 1467
st r5, r1, 6 // icount 1468
nop // to align meminst icount 1469
ld r4, r0, 14 // icount 1470
nop // to align meminst icount 1471
ld r6, r0, 6 // icount 1472
nop // to align meminst icount 1473
stu r3, r0, 14 // icount 1474
nop // to align meminst icount 1475
stu r3, r1, -14 // icount 1476
nop // to align meminst icount 1477
ld r6, r0, 2 // icount 1478
nop // to align meminst icount 1479
st r3, r0, 0 // icount 1480
nop // to align meminst icount 1481
ld r6, r1, 0 // icount 1482
nop // to align meminst icount 1483
stu r3, r0, 6 // icount 1484
nop // to align meminst icount 1485
st r4, r1, -14 // icount 1486
nop // to align meminst icount 1487
ld r3, r1, -4 // icount 1488
nop // to align meminst icount 1489
stu r3, r0, 14 // icount 1490
nop // to align meminst icount 1491
stu r5, r0, 2 // icount 1492
nop // to align meminst icount 1493
st r3, r1, 4 // icount 1494
nop // to align meminst icount 1495
ld r3, r0, -4 // icount 1496
nop // to align meminst icount 1497
ld r6, r1, -10 // icount 1498
nop // to align meminst icount 1499
ld r6, r1, 0 // icount 1500
nop // to align meminst icount 1501
ld r4, r0, 14 // icount 1502
nop // to align meminst icount 1503
ld r2, r0, -4 // icount 1504
nop // to align meminst icount 1505
stu r4, r1, -12 // icount 1506
nop // to align meminst icount 1507
ld r5, r0, -14 // icount 1508
nop // to align meminst icount 1509
ld r4, r1, -4 // icount 1510
nop // to align meminst icount 1511
st r5, r1, -16 // icount 1512
nop // to align meminst icount 1513
ld r5, r1, 6 // icount 1514
nop // to align meminst icount 1515
ld r2, r1, -10 // icount 1516
nop // to align meminst icount 1517
ld r3, r0, 0 // icount 1518
nop // to align meminst icount 1519
stu r4, r0, 0 // icount 1520
nop // to align meminst icount 1521
stu r4, r1, -8 // icount 1522
nop // to align meminst icount 1523
ld r5, r1, -12 // icount 1524
nop // to align meminst icount 1525
ld r5, r0, -8 // icount 1526
nop // to align meminst icount 1527
st r4, r0, -6 // icount 1528
nop // to align meminst icount 1529
ld r5, r0, 12 // icount 1530
stu r3, r0, -12 // icount 1531
lbi r6, 0 // icount 1532
lbi r3, 0 // icount 1533
nop // to align branch icount 1534
beqz r3, 8 // icount 1535
srl r2, r3, r3 // icount 1536
xori r2, r6, 5 // icount 1537
seq r5, r0, r4 // icount 1538
xor r2, r2, r0 // icount 1539
sub r6, r3, r7 // icount 1540
seq r7, r3, r2 // icount 1541
add r7, r0, r7 // icount 1542
nop // to align meminst icount 1543
rori r7, r5, 6 // icount 1544
nop // to align meminst icount 1545
ld r5, r0, -6 // icount 1546
nop // to align meminst icount 1547
stu r2, r0, -16 // icount 1548
nop // to align meminst icount 1549
ld r2, r1, 8 // icount 1550
nop // to align meminst icount 1551
ld r5, r0, -16 // icount 1552
nop // to align meminst icount 1553
st r2, r1, 0 // icount 1554
nop // to align meminst icount 1555
st r5, r0, -14 // icount 1556
nop // to align meminst icount 1557
ld r4, r1, 0 // icount 1558
nop // to align meminst icount 1559
ld r6, r0, -10 // icount 1560
nop // to align meminst icount 1561
st r5, r0, -14 // icount 1562
nop // to align meminst icount 1563
ld r6, r0, 4 // icount 1564
nop // to align meminst icount 1565
ld r2, r1, 12 // icount 1566
nop // to align meminst icount 1567
stu r3, r0, 4 // icount 1568
nop // to align meminst icount 1569
ld r3, r1, -2 // icount 1570
nop // to align meminst icount 1571
ld r5, r0, 14 // icount 1572
nop // to align meminst icount 1573
stu r3, r0, 10 // icount 1574
nop // to align meminst icount 1575
ld r6, r0, 0 // icount 1576
nop // to align meminst icount 1577
ld r6, r1, 6 // icount 1578
nop // to align meminst icount 1579
stu r5, r0, 8 // icount 1580
nop // to align meminst icount 1581
st r2, r1, -10 // icount 1582
ld r6, r1, -8 // icount 1583
addi r0, r0, 12 // change base addr // icount 1584
nop // to align meminst icount 1585
ld r6, r0, -10 // icount 1586
nop // to align meminst icount 1587
ld r4, r1, 2 // icount 1588
nop // to align meminst icount 1589
ld r5, r1, 8 // icount 1590
nop // to align meminst icount 1591
ld r5, r1, 0 // icount 1592
nop // to align meminst icount 1593
st r6, r1, -8 // icount 1594
nop // to align meminst icount 1595
ld r2, r1, 12 // icount 1596
nop // to align meminst icount 1597
ld r3, r1, -6 // icount 1598
nop // to align meminst icount 1599
stu r6, r1, 0 // icount 1600
nop // to align meminst icount 1601
st r6, r0, -12 // icount 1602
nop // to align meminst icount 1603
stu r3, r0, 14 // icount 1604
nop // to align meminst icount 1605
stu r6, r0, 14 // icount 1606
nop // to align meminst icount 1607
ld r3, r1, -14 // icount 1608
nop // to align meminst icount 1609
stu r4, r1, 2 // icount 1610
nop // to align meminst icount 1611
ld r5, r1, -12 // icount 1612
nop // to align meminst icount 1613
st r4, r1, 4 // icount 1614
nop // to align meminst icount 1615
st r2, r0, -10 // icount 1616
nop // to align meminst icount 1617
st r2, r0, -8 // icount 1618
nop // to align meminst icount 1619
ld r2, r0, 6 // icount 1620
ld r6, r1, -4 // icount 1621
lbi r7, 0 // icount 1622
lbi r6, 0 // icount 1623
nop // to align branch icount 1624
bnez r4, 8 // icount 1625
slbi r5, 5 // icount 1626
sle r5, r6, r7 // icount 1627
rori r7, r1, 10 // icount 1628
nop // to align meminst icount 1629
andni r3, r3, 1 // icount 1630
st r2, r3, 8 // icount 1631
addi r3, r5, 6 // icount 1632
rol r7, r0, r1 // icount 1633
andni r5, r5, 1 // icount 1634
stu r4, r5, 10 // icount 1635
srli r5, r2, 10 // icount 1636
nop // to align meminst icount 1637
st r6, r0, -8 // icount 1638
nop // to align meminst icount 1639
ld r3, r0, 14 // icount 1640
nop // to align meminst icount 1641
ld r4, r1, -4 // icount 1642
nop // to align meminst icount 1643
stu r5, r0, -14 // icount 1644
nop // to align meminst icount 1645
ld r6, r0, -8 // icount 1646
nop // to align meminst icount 1647
ld r3, r0, 14 // icount 1648
nop // to align meminst icount 1649
st r2, r0, -2 // icount 1650
nop // to align meminst icount 1651
ld r4, r1, -16 // icount 1652
nop // to align meminst icount 1653
st r4, r0, 2 // icount 1654
nop // to align meminst icount 1655
st r2, r0, -16 // icount 1656
nop // to align meminst icount 1657
stu r2, r0, -2 // icount 1658
nop // to align meminst icount 1659
stu r4, r0, 8 // icount 1660
nop // to align meminst icount 1661
ld r4, r0, 4 // icount 1662
nop // to align meminst icount 1663
stu r6, r1, -4 // icount 1664
nop // to align meminst icount 1665
ld r4, r1, 10 // icount 1666
nop // to align meminst icount 1667
st r2, r1, 2 // icount 1668
nop // to align meminst icount 1669
stu r3, r0, -16 // icount 1670
nop // to align meminst icount 1671
st r2, r1, 0 // icount 1672
nop // to align meminst icount 1673
ld r5, r0, -14 // icount 1674
nop // to align meminst icount 1675
st r2, r1, 10 // icount 1676
nop // to align meminst icount 1677
ld r6, r1, 10 // icount 1678
nop // to align meminst icount 1679
ld r3, r1, -2 // icount 1680
nop // to align meminst icount 1681
ld r5, r1, 12 // icount 1682
nop // to align meminst icount 1683
stu r5, r0, -16 // icount 1684
nop // to align meminst icount 1685
ld r4, r0, 6 // icount 1686
nop // to align meminst icount 1687
ld r3, r0, -4 // icount 1688
nop // to align meminst icount 1689
st r6, r0, 4 // icount 1690
nop // to align meminst icount 1691
ld r6, r1, -16 // icount 1692
nop // to align meminst icount 1693
stu r3, r0, 10 // icount 1694
nop // to align meminst icount 1695
ld r3, r0, -12 // icount 1696
nop // to align meminst icount 1697
stu r3, r1, 12 // icount 1698
nop // to align meminst icount 1699
stu r3, r0, -16 // icount 1700
nop // to align meminst icount 1701
st r2, r0, -10 // icount 1702
nop // to align meminst icount 1703
stu r4, r1, 4 // icount 1704
nop // to align meminst icount 1705
ld r2, r0, 0 // icount 1706
nop // to align meminst icount 1707
stu r6, r0, 12 // icount 1708
nop // to align meminst icount 1709
stu r3, r1, -4 // icount 1710
nop // to align meminst icount 1711
ld r2, r1, -14 // icount 1712
nop // to align meminst icount 1713
ld r4, r0, -8 // icount 1714
nop // to align meminst icount 1715
stu r6, r0, -4 // icount 1716
nop // to align meminst icount 1717
ld r5, r0, 2 // icount 1718
nop // to align meminst icount 1719
ld r5, r0, 10 // icount 1720
nop // to align meminst icount 1721
ld r2, r1, -8 // icount 1722
nop // to align meminst icount 1723
ld r4, r0, -6 // icount 1724
st r2, r0, -12 // icount 1725
slbi r4, 12 // icount 1726
nop // to align meminst icount 1727
ld r4, r0, -8 // icount 1728
nop // to align meminst icount 1729
st r2, r0, 0 // icount 1730
nop // to align meminst icount 1731
st r6, r1, 0 // icount 1732
nop // to align meminst icount 1733
ld r3, r1, -16 // icount 1734
nop // to align meminst icount 1735
st r3, r1, -4 // icount 1736
nop // to align meminst icount 1737
stu r2, r1, 14 // icount 1738
nop // to align meminst icount 1739
stu r6, r0, 12 // icount 1740
nop // to align meminst icount 1741
st r4, r1, 0 // icount 1742
nop // to align meminst icount 1743
st r4, r0, 0 // icount 1744
nop // to align meminst icount 1745
ld r4, r0, -12 // icount 1746
nop // to align meminst icount 1747
ld r4, r1, -12 // icount 1748
nop // to align meminst icount 1749
stu r5, r1, 6 // icount 1750
nop // to align meminst icount 1751
st r4, r0, 0 // icount 1752
nop // to align meminst icount 1753
ld r2, r1, -2 // icount 1754
nop // to align meminst icount 1755
ld r4, r1, 10 // icount 1756
ld r5, r0, 6 // icount 1757
addi r0, r0, -6 // change base addr // icount 1758
nop // to align meminst icount 1759
ld r5, r0, 0 // icount 1760
nop // to align meminst icount 1761
ld r3, r1, -4 // icount 1762
nop // to align meminst icount 1763
ld r3, r1, -6 // icount 1764
nop // to align meminst icount 1765
stu r3, r1, -16 // icount 1766
nop // to align meminst icount 1767
st r5, r1, -10 // icount 1768
nop // to align meminst icount 1769
ld r6, r1, -10 // icount 1770
nop // to align meminst icount 1771
ld r6, r1, -12 // icount 1772
nop // to align meminst icount 1773
ld r2, r1, -6 // icount 1774
nop // to align meminst icount 1775
st r3, r0, 8 // icount 1776
nop // to align meminst icount 1777
stu r6, r1, -12 // icount 1778
nop // to align meminst icount 1779
stu r3, r0, 6 // icount 1780
nop // to align meminst icount 1781
ld r3, r0, 14 // icount 1782
nop // to align meminst icount 1783
stu r5, r0, 10 // icount 1784
nop // to align meminst icount 1785
st r3, r1, 10 // icount 1786
nop // to align meminst icount 1787
st r6, r0, -4 // icount 1788
nop // to align meminst icount 1789
ld r4, r0, 10 // icount 1790
nop // to align meminst icount 1791
st r3, r1, -16 // icount 1792
nop // to align meminst icount 1793
ld r3, r1, 12 // icount 1794
nop // to align meminst icount 1795
stu r6, r0, -16 // icount 1796
nop // to align meminst icount 1797
stu r3, r1, -14 // icount 1798
nop // to align meminst icount 1799
st r6, r1, 6 // icount 1800
nop // to align meminst icount 1801
ld r5, r0, -8 // icount 1802
nop // to align meminst icount 1803
stu r6, r1, -12 // icount 1804
nop // to align meminst icount 1805
stu r2, r1, -4 // icount 1806
nop // to align meminst icount 1807
ld r2, r0, -12 // icount 1808
nop // to align meminst icount 1809
st r2, r0, 8 // icount 1810
nop // to align meminst icount 1811
ld r4, r1, 10 // icount 1812
nop // to align meminst icount 1813
ld r5, r1, 6 // icount 1814
nop // to align meminst icount 1815
ld r6, r1, 8 // icount 1816
nop // to align meminst icount 1817
stu r6, r1, 12 // icount 1818
nop // to align meminst icount 1819
ld r5, r1, 12 // icount 1820
nop // to align meminst icount 1821
ld r3, r0, -6 // icount 1822
nop // to align meminst icount 1823
st r6, r1, 14 // icount 1824
nop // to align meminst icount 1825
ld r3, r0, 4 // icount 1826
st r6, r1, 4 // icount 1827
lbi r6, 0 // icount 1828
lbi r4, 0 // icount 1829
nop // to align branch icount 1830
bgez r1, 24 // icount 1831
andni r2, r6, 7 // icount 1832
lbi r2, 8 // icount 1833
sub r2, r6, r7 // icount 1834
andn r3, r2, r3 // icount 1835
andni r5, r5, 1 // icount 1836
ld r3, r5, 12 // icount 1837
seq r4, r0, r1 // icount 1838
nop // to align meminst icount 1839
andni r5, r5, 1 // icount 1840
ld r5, r5, 10 // icount 1841
srli r6, r7, 7 // icount 1842
subi r2, r5, 3 // icount 1843
srl r3, r6, r3 // icount 1844
sle r4, r0, r7 // icount 1845
srl r7, r4, r0 // icount 1846
xori r6, r2, 11 // icount 1847
ror r4, r7, r6 // icount 1848
seq r6, r7, r5 // icount 1849
andni r2, r7, 10 // icount 1850
rori r2, r1, 7 // icount 1851
srl r3, r5, r1 // icount 1852
roli r7, r0, 13 // icount 1853
ror r2, r7, r6 // icount 1854
srl r5, r3, r3 // icount 1855
sco r6, r3, r4 // icount 1856
sub r4, r6, r2 // icount 1857
subi r3, r5, 4 // icount 1858
nop // to align meminst icount 1859
st r3, r0, 2 // icount 1860
nop // to align meminst icount 1861
st r3, r1, -16 // icount 1862
nop // to align meminst icount 1863
st r2, r0, 14 // icount 1864
nop // to align meminst icount 1865
st r5, r0, -2 // icount 1866
nop // to align meminst icount 1867
stu r4, r0, 0 // icount 1868
nop // to align meminst icount 1869
stu r3, r1, -10 // icount 1870
nop // to align meminst icount 1871
stu r2, r0, 6 // icount 1872
nop // to align meminst icount 1873
stu r6, r1, -4 // icount 1874
nop // to align meminst icount 1875
ld r3, r0, 14 // icount 1876
nop // to align meminst icount 1877
ld r5, r1, 2 // icount 1878
nop // to align meminst icount 1879
ld r4, r1, 6 // icount 1880
nop // to align meminst icount 1881
stu r2, r1, 4 // icount 1882
nop // to align meminst icount 1883
stu r3, r1, -2 // icount 1884
nop // to align meminst icount 1885
stu r2, r1, -4 // icount 1886
stu r2, r1, 2 // icount 1887
rol r3, r2, r4 // icount 1888
nop // to align meminst icount 1889
ld r5, r0, 12 // icount 1890
nop // to align meminst icount 1891
stu r3, r1, 4 // icount 1892
nop // to align meminst icount 1893
ld r2, r0, 8 // icount 1894
nop // to align meminst icount 1895
ld r4, r1, -14 // icount 1896
nop // to align meminst icount 1897
st r5, r1, 0 // icount 1898
nop // to align meminst icount 1899
stu r5, r1, -8 // icount 1900
nop // to align meminst icount 1901
ld r2, r1, 14 // icount 1902
nop // to align meminst icount 1903
ld r3, r1, -4 // icount 1904
nop // to align meminst icount 1905
st r5, r1, 2 // icount 1906
nop // to align meminst icount 1907
stu r6, r0, -12 // icount 1908
nop // to align meminst icount 1909
ld r4, r0, 10 // icount 1910
nop // to align meminst icount 1911
ld r3, r1, -8 // icount 1912
nop // to align meminst icount 1913
st r4, r0, 0 // icount 1914
ld r3, r0, 12 // icount 1915
sle r7, r3, r1 // icount 1916
nop // to align meminst icount 1917
st r4, r1, -2 // icount 1918
nop // to align meminst icount 1919
st r6, r0, -4 // icount 1920
nop // to align meminst icount 1921
ld r4, r1, 2 // icount 1922
nop // to align meminst icount 1923
stu r4, r1, 0 // icount 1924
nop // to align meminst icount 1925
ld r4, r1, 12 // icount 1926
nop // to align meminst icount 1927
stu r2, r1, 4 // icount 1928
nop // to align meminst icount 1929
stu r4, r0, -8 // icount 1930
nop // to align meminst icount 1931
st r2, r0, -16 // icount 1932
nop // to align meminst icount 1933
st r4, r1, 12 // icount 1934
nop // to align meminst icount 1935
st r4, r1, -2 // icount 1936
nop // to align meminst icount 1937
ld r2, r0, 4 // icount 1938
nop // to align meminst icount 1939
st r4, r1, 4 // icount 1940
nop // to align meminst icount 1941
ld r5, r1, 10 // icount 1942
nop // to align meminst icount 1943
ld r6, r1, -16 // icount 1944
nop // to align meminst icount 1945
ld r6, r0, 12 // icount 1946
nop // to align meminst icount 1947
stu r4, r0, 14 // icount 1948
nop // to align meminst icount 1949
ld r6, r0, 2 // icount 1950
nop // to align meminst icount 1951
st r2, r0, 6 // icount 1952
nop // to align meminst icount 1953
st r5, r0, -4 // icount 1954
nop // to align meminst icount 1955
ld r3, r1, 14 // icount 1956
nop // to align meminst icount 1957
st r2, r1, -4 // icount 1958
nop // to align meminst icount 1959
ld r2, r1, 6 // icount 1960
nop // to align meminst icount 1961
ld r2, r1, 0 // icount 1962
nop // to align meminst icount 1963
stu r3, r0, 10 // icount 1964
nop // to align meminst icount 1965
stu r3, r0, 0 // icount 1966
nop // to align meminst icount 1967
ld r5, r1, -14 // icount 1968
nop // to align meminst icount 1969
ld r2, r0, 0 // icount 1970
nop // to align meminst icount 1971
ld r5, r1, -6 // icount 1972
nop // to align meminst icount 1973
ld r3, r1, 2 // icount 1974
nop // to align meminst icount 1975
st r5, r1, -16 // icount 1976
ld r5, r0, -4 // icount 1977
addi r0, r0, -6 // change base addr // icount 1978
nop // to align meminst icount 1979
ld r2, r1, 10 // icount 1980
nop // to align meminst icount 1981
stu r5, r1, -12 // icount 1982
nop // to align meminst icount 1983
stu r3, r1, -2 // icount 1984
nop // to align meminst icount 1985
stu r5, r0, -6 // icount 1986
nop // to align meminst icount 1987
ld r4, r0, 8 // icount 1988
nop // to align meminst icount 1989
stu r2, r0, -2 // icount 1990
nop // to align meminst icount 1991
stu r4, r0, -4 // icount 1992
nop // to align meminst icount 1993
ld r4, r1, -12 // icount 1994
nop // to align meminst icount 1995
st r2, r0, 14 // icount 1996
nop // to align meminst icount 1997
st r6, r1, 12 // icount 1998
nop // to align meminst icount 1999
ld r5, r0, -2 // icount 2000
nop // to align meminst icount 2001
ld r3, r0, 4 // icount 2002
nop // to align meminst icount 2003
ld r2, r1, -8 // icount 2004
nop // to align meminst icount 2005
ld r2, r0, -16 // icount 2006
nop // to align meminst icount 2007
ld r5, r0, 12 // icount 2008
stu r4, r0, 2 // icount 2009
addi r0, r0, -14 // change base addr // icount 2010
nop // to align meminst icount 2011
ld r2, r0, -10 // icount 2012
nop // to align meminst icount 2013
st r5, r0, -14 // icount 2014
stu r4, r1, -6 // icount 2015
addi r1, r1, 10 // change base addr // icount 2016
nop // to align meminst icount 2017
st r2, r0, -8 // icount 2018
nop // to align meminst icount 2019
ld r5, r0, -2 // icount 2020
nop // to align meminst icount 2021
st r4, r0, 6 // icount 2022
nop // to align meminst icount 2023
st r2, r0, 2 // icount 2024
nop // to align meminst icount 2025
ld r3, r0, 14 // icount 2026
nop // to align meminst icount 2027
ld r2, r1, -16 // icount 2028
ld r6, r1, -2 // icount 2029
addi r0, r0, -2 // change base addr // icount 2030
st r6, r1, -6 // icount 2031
roli r7, r0, 13 // icount 2032
nop // to align meminst icount 2033
ld r4, r0, 10 // icount 2034
nop // to align meminst icount 2035
stu r4, r0, 0 // icount 2036
nop // to align meminst icount 2037
ld r4, r0, -2 // icount 2038
nop // to align meminst icount 2039
ld r2, r1, 0 // icount 2040
nop // to align meminst icount 2041
ld r5, r1, 10 // icount 2042
ld r2, r0, 6 // icount 2043
ror r4, r6, r7 // icount 2044
nop // to align meminst icount 2045
ld r3, r1, -12 // icount 2046
nop // to align meminst icount 2047
stu r6, r0, 0 // icount 2048
nop // to align meminst icount 2049
stu r4, r1, -16 // icount 2050
nop // to align meminst icount 2051
ld r5, r1, 6 // icount 2052
nop // to align meminst icount 2053
ld r4, r1, 4 // icount 2054
nop // to align meminst icount 2055
st r6, r1, 0 // icount 2056
nop // to align meminst icount 2057
ld r4, r0, 2 // icount 2058
nop // to align meminst icount 2059
stu r2, r0, 6 // icount 2060
nop // to align meminst icount 2061
ld r3, r1, -2 // icount 2062
nop // to align meminst icount 2063
ld r3, r0, -8 // icount 2064
nop // to align meminst icount 2065
ld r2, r1, 0 // icount 2066
nop // to align meminst icount 2067
ld r6, r0, -6 // icount 2068
nop // to align meminst icount 2069
st r4, r1, -4 // icount 2070
nop // to align meminst icount 2071
ld r2, r0, -2 // icount 2072
nop // to align meminst icount 2073
st r6, r1, -10 // icount 2074
nop // to align meminst icount 2075
ld r4, r0, 8 // icount 2076
nop // to align meminst icount 2077
ld r2, r1, -14 // icount 2078
nop // to align meminst icount 2079
ld r3, r1, 12 // icount 2080
nop // to align meminst icount 2081
ld r2, r1, -4 // icount 2082
nop // to align meminst icount 2083
stu r4, r1, 2 // icount 2084
nop // to align meminst icount 2085
st r2, r1, 8 // icount 2086
nop // to align meminst icount 2087
ld r6, r0, -8 // icount 2088
nop // to align meminst icount 2089
ld r5, r1, 10 // icount 2090
stu r6, r1, 8 // icount 2091
andni r5, r5, 1 // icount 2092
nop // to align meminst icount 2093
ld r4, r5, 8 // icount 2094
nop // to align meminst icount 2095
ld r6, r1, 2 // icount 2096
nop // to align meminst icount 2097
ld r2, r1, -16 // icount 2098
nop // to align meminst icount 2099
ld r4, r0, 8 // icount 2100
nop // to align meminst icount 2101
stu r4, r0, -12 // icount 2102
nop // to align meminst icount 2103
ld r5, r0, 14 // icount 2104
nop // to align meminst icount 2105
stu r6, r1, -6 // icount 2106
nop // to align meminst icount 2107
st r2, r1, 10 // icount 2108
nop // to align meminst icount 2109
stu r2, r0, 8 // icount 2110
nop // to align meminst icount 2111
st r5, r1, 8 // icount 2112
nop // to align meminst icount 2113
ld r6, r1, 2 // icount 2114
nop // to align meminst icount 2115
st r4, r0, -16 // icount 2116
nop // to align meminst icount 2117
ld r2, r0, -6 // icount 2118
nop // to align meminst icount 2119
st r4, r0, -4 // icount 2120
nop // to align meminst icount 2121
ld r4, r0, -2 // icount 2122
nop // to align meminst icount 2123
ld r5, r1, 0 // icount 2124
nop // to align meminst icount 2125
st r5, r0, -16 // icount 2126
nop // to align meminst icount 2127
stu r3, r0, 8 // icount 2128
stu r5, r0, 8 // icount 2129
lbi r5, 0 // icount 2130
lbi r7, 0 // icount 2131
nop // to align branch icount 2132
bnez r5, 4 // icount 2133
andni r2, r2, 1 // icount 2134
st r6, r2, 4 // icount 2135
addi r5, r6, 13 // icount 2136
sco r2, r0, r3 // icount 2137
seq r4, r6, r6 // icount 2138
nop // to align meminst icount 2139
ld r6, r1, -16 // icount 2140
nop // to align meminst icount 2141
ld r3, r0, 8 // icount 2142
nop // to align meminst icount 2143
st r5, r1, -4 // icount 2144
nop // to align meminst icount 2145
stu r6, r0, -12 // icount 2146
nop // to align meminst icount 2147
stu r2, r0, -10 // icount 2148
nop // to align meminst icount 2149
st r2, r1, 14 // icount 2150
nop // to align meminst icount 2151
st r2, r0, 8 // icount 2152
nop // to align meminst icount 2153
ld r4, r0, 0 // icount 2154
nop // to align meminst icount 2155
ld r2, r1, 12 // icount 2156
nop // to align meminst icount 2157
ld r5, r1, 2 // icount 2158
nop // to align meminst icount 2159
ld r4, r1, 10 // icount 2160
nop // to align meminst icount 2161
st r4, r0, 4 // icount 2162
nop // to align meminst icount 2163
st r6, r1, 2 // icount 2164
nop // to align meminst icount 2165
stu r5, r0, -8 // icount 2166
nop // to align meminst icount 2167
ld r6, r0, -14 // icount 2168
nop // to align meminst icount 2169
ld r6, r0, 4 // icount 2170
nop // to align meminst icount 2171
stu r3, r1, -16 // icount 2172
nop // to align meminst icount 2173
stu r4, r0, 14 // icount 2174
nop // to align meminst icount 2175
stu r5, r0, -16 // icount 2176
nop // to align meminst icount 2177
st r6, r1, -2 // icount 2178
nop // to align meminst icount 2179
ld r4, r0, 2 // icount 2180
nop // to align meminst icount 2181
ld r2, r1, 2 // icount 2182
nop // to align meminst icount 2183
ld r6, r1, -14 // icount 2184
nop // to align meminst icount 2185
ld r2, r0, 4 // icount 2186
nop // to align meminst icount 2187
stu r2, r0, -16 // icount 2188
nop // to align meminst icount 2189
st r5, r0, -16 // icount 2190
nop // to align meminst icount 2191
ld r6, r1, -6 // icount 2192
st r5, r0, -6 // icount 2193
halt // icount 2194
|
.size 8000
.text@48
jp lstatint
.text@100
jp lbegin
.data@143
80
.text@150
lbegin:
ld a, ff
ldff(45), a
ld b, 40
call lwaitly_b
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 44
ldff(45), a
.text@1000
lstatint:
nop
.text@1020
ld a, 77
ldff(44), a
ldff a, (41)
jp lprint_a
.text@7000
lprint_a:
push af
ld b, 91
call lwaitly_b
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, 00
lprint_copytiles:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jrnz lprint_copytiles
pop af
ld b, a
srl a
srl a
srl a
srl a
ld(9800), a
ld a, b
and a, 0f
ld(9801), a
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
xor a, a
ldff(69), a
ldff(69), a
ldff(43), a
ld a, 91
ldff(40), a
lprint_limbo:
jr lprint_limbo
.text@7400
lwaitly_b:
ld c, 44
lwaitly_b_loop:
ldff a, (c)
cmp a, b
jrnz lwaitly_b_loop
ret
.data@7a00
00 00 7f 7f 41 41 41 41
41 41 41 41 41 41 7f 7f
00 00 08 08 08 08 08 08
08 08 08 08 08 08 08 08
00 00 7f 7f 01 01 01 01
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 01 01 01 01
3f 3f 01 01 01 01 7f 7f
00 00 41 41 41 41 41 41
7f 7f 01 01 01 01 01 01
00 00 7f 7f 40 40 40 40
7e 7e 01 01 01 01 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 41 41 41 41 7f 7f
00 00 7f 7f 01 01 02 02
04 04 08 08 10 10 10 10
00 00 3e 3e 41 41 41 41
3e 3e 41 41 41 41 3e 3e
00 00 7f 7f 41 41 41 41
7f 7f 01 01 01 01 7f 7f
00 00 08 08 22 22 41 41
7f 7f 41 41 41 41 41 41
00 00 7e 7e 41 41 41 41
7e 7e 41 41 41 41 7e 7e
00 00 3e 3e 41 41 40 40
40 40 40 40 41 41 3e 3e
00 00 7e 7e 41 41 41 41
41 41 41 41 41 41 7e 7e
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 7f 7f
00 00 7f 7f 40 40 40 40
7f 7f 40 40 40 40 40 40
|
// Copyright (c) 2012 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 <time.h>
#include <algorithm>
#include <sstream>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/timer/timer.h"
#include "base/values.h"
#include "chrome/browser/net/predictor.h"
#include "chrome/browser/net/spdyproxy/proxy_advisor.h"
#include "chrome/browser/net/url_info.h"
#include "chrome/common/net/predictor_common.h"
#include "content/public/test/test_browser_thread.h"
#include "net/base/address_list.h"
#include "net/base/winsock_init.h"
#include "net/dns/mock_host_resolver.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using base::Time;
using base::TimeDelta;
using content::BrowserThread;
namespace chrome_browser_net {
class WaitForResolutionHelper;
typedef base::RepeatingTimer<WaitForResolutionHelper> HelperTimer;
class WaitForResolutionHelper {
public:
WaitForResolutionHelper(Predictor* predictor, const UrlList& hosts,
HelperTimer* timer, int checks_until_quit)
: predictor_(predictor),
hosts_(hosts),
timer_(timer),
checks_until_quit_(checks_until_quit) {
}
void CheckIfResolutionsDone() {
if (--checks_until_quit_ > 0) {
for (UrlList::const_iterator i = hosts_.begin(); i != hosts_.end(); ++i)
if (predictor_->GetResolutionDuration(*i) ==
UrlInfo::NullDuration())
return; // We don't have resolution for that host.
}
// When all hostnames have been resolved, or we've hit the limit,
// exit the loop.
timer_->Stop();
base::MessageLoop::current()->Quit();
delete timer_;
delete this;
}
private:
Predictor* predictor_;
const UrlList hosts_;
HelperTimer* timer_;
int checks_until_quit_;
};
class PredictorTest : public testing::Test {
public:
PredictorTest()
: ui_thread_(BrowserThread::UI, &loop_),
io_thread_(BrowserThread::IO, &loop_),
host_resolver_(new net::MockCachingHostResolver()) {
}
protected:
virtual void SetUp() {
#if defined(OS_WIN)
net::EnsureWinsockInit();
#endif
Predictor::set_max_parallel_resolves(
Predictor::kMaxSpeculativeParallelResolves);
Predictor::set_max_queueing_delay(
Predictor::kMaxSpeculativeResolveQueueDelayMs);
// Since we are using a caching HostResolver, the following latencies will
// only be incurred by the first request, after which the result will be
// cached internally by |host_resolver_|.
net::RuleBasedHostResolverProc* rules = host_resolver_->rules();
rules->AddRuleWithLatency("www.google.com", "127.0.0.1", 50);
rules->AddRuleWithLatency("gmail.google.com.com", "127.0.0.1", 70);
rules->AddRuleWithLatency("mail.google.com", "127.0.0.1", 44);
rules->AddRuleWithLatency("gmail.com", "127.0.0.1", 63);
}
void WaitForResolution(Predictor* predictor, const UrlList& hosts) {
HelperTimer* timer = new HelperTimer();
// By default allow the loop to run for a minute -- 600 iterations.
timer->Start(FROM_HERE, TimeDelta::FromMilliseconds(100),
new WaitForResolutionHelper(predictor, hosts, timer, 600),
&WaitForResolutionHelper::CheckIfResolutionsDone);
base::MessageLoop::current()->Run();
}
void WaitForResolutionWithLimit(
Predictor* predictor, const UrlList& hosts, int limit) {
HelperTimer* timer = new HelperTimer();
timer->Start(FROM_HERE, TimeDelta::FromMilliseconds(100),
new WaitForResolutionHelper(predictor, hosts, timer, limit),
&WaitForResolutionHelper::CheckIfResolutionsDone);
base::MessageLoop::current()->Run();
}
private:
// IMPORTANT: do not move this below |host_resolver_|; the host resolver
// must not outlive the message loop, otherwise bad things can happen
// (like posting to a deleted message loop).
base::MessageLoopForUI loop_;
content::TestBrowserThread ui_thread_;
content::TestBrowserThread io_thread_;
protected:
scoped_ptr<net::MockCachingHostResolver> host_resolver_;
};
//------------------------------------------------------------------------------
TEST_F(PredictorTest, StartupShutdownTest) {
Predictor testing_master(true);
testing_master.Shutdown();
}
TEST_F(PredictorTest, ShutdownWhenResolutionIsPendingTest) {
scoped_ptr<net::HostResolver> host_resolver(new net::HangingHostResolver());
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver.get());
GURL localhost("http://localhost:80");
UrlList names;
names.push_back(localhost);
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
base::MessageLoop::current()->PostDelayedTask(
FROM_HERE,
base::MessageLoop::QuitClosure(),
base::TimeDelta::FromMilliseconds(500));
base::MessageLoop::current()->Run();
EXPECT_FALSE(testing_master.WasFound(localhost));
testing_master.Shutdown();
// Clean up after ourselves.
base::MessageLoop::current()->RunUntilIdle();
}
TEST_F(PredictorTest, SingleLookupTest) {
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver_.get());
GURL goog("http://www.google.com:80");
UrlList names;
names.push_back(goog);
// Try to flood the predictor with many concurrent requests.
for (int i = 0; i < 10; i++)
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
WaitForResolution(&testing_master, names);
EXPECT_TRUE(testing_master.WasFound(goog));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_GT(testing_master.peak_pending_lookups(), names.size() / 2);
EXPECT_LE(testing_master.peak_pending_lookups(), names.size());
EXPECT_LE(testing_master.peak_pending_lookups(),
testing_master.max_concurrent_dns_lookups());
testing_master.Shutdown();
}
TEST_F(PredictorTest, ConcurrentLookupTest) {
host_resolver_->rules()->AddSimulatedFailure("*.notfound");
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver_.get());
GURL goog("http://www.google.com:80"),
goog2("http://gmail.google.com.com:80"),
goog3("http://mail.google.com:80"),
goog4("http://gmail.com:80");
GURL bad1("http://bad1.notfound:80"),
bad2("http://bad2.notfound:80");
UrlList names;
names.push_back(goog);
names.push_back(goog3);
names.push_back(bad1);
names.push_back(goog2);
names.push_back(bad2);
names.push_back(goog4);
names.push_back(goog);
// Try to flood the predictor with many concurrent requests.
for (int i = 0; i < 10; i++)
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
WaitForResolution(&testing_master, names);
EXPECT_TRUE(testing_master.WasFound(goog));
EXPECT_TRUE(testing_master.WasFound(goog3));
EXPECT_TRUE(testing_master.WasFound(goog2));
EXPECT_TRUE(testing_master.WasFound(goog4));
EXPECT_FALSE(testing_master.WasFound(bad1));
EXPECT_FALSE(testing_master.WasFound(bad2));
base::MessageLoop::current()->RunUntilIdle();
EXPECT_FALSE(testing_master.WasFound(bad1));
EXPECT_FALSE(testing_master.WasFound(bad2));
EXPECT_LE(testing_master.peak_pending_lookups(), names.size());
EXPECT_LE(testing_master.peak_pending_lookups(),
testing_master.max_concurrent_dns_lookups());
testing_master.Shutdown();
}
TEST_F(PredictorTest, MassiveConcurrentLookupTest) {
host_resolver_->rules()->AddSimulatedFailure("*.notfound");
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver_.get());
UrlList names;
for (int i = 0; i < 100; i++)
names.push_back(GURL(
"http://host" + base::IntToString(i) + ".notfound:80"));
// Try to flood the predictor with many concurrent requests.
for (int i = 0; i < 10; i++)
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
WaitForResolution(&testing_master, names);
base::MessageLoop::current()->RunUntilIdle();
EXPECT_LE(testing_master.peak_pending_lookups(), names.size());
EXPECT_LE(testing_master.peak_pending_lookups(),
testing_master.max_concurrent_dns_lookups());
testing_master.Shutdown();
}
//------------------------------------------------------------------------------
// Functions to help synthesize and test serializations of subresource referrer
// lists.
// Return a motivation_list if we can find one for the given motivating_host (or
// NULL if a match is not found).
static const base::ListValue* FindSerializationMotivation(
const GURL& motivation,
const base::ListValue* referral_list) {
CHECK_LT(0u, referral_list->GetSize()); // Room for version.
int format_version = -1;
CHECK(referral_list->GetInteger(0, &format_version));
CHECK_EQ(Predictor::kPredictorReferrerVersion, format_version);
const base::ListValue* motivation_list(NULL);
for (size_t i = 1; i < referral_list->GetSize(); ++i) {
referral_list->GetList(i, &motivation_list);
std::string existing_spec;
EXPECT_TRUE(motivation_list->GetString(0, &existing_spec));
if (motivation == GURL(existing_spec))
return motivation_list;
}
return NULL;
}
static base::ListValue* FindSerializationMotivation(
const GURL& motivation,
base::ListValue* referral_list) {
return const_cast<base::ListValue*>(FindSerializationMotivation(
motivation, static_cast<const base::ListValue*>(referral_list)));
}
// Create a new empty serialization list.
static base::ListValue* NewEmptySerializationList() {
base::ListValue* list = new base::ListValue;
list->Append(
new base::FundamentalValue(Predictor::kPredictorReferrerVersion));
return list;
}
// Add a motivating_url and a subresource_url to a serialized list, using
// this given latency. This is a helper function for quickly building these
// lists.
static void AddToSerializedList(const GURL& motivation,
const GURL& subresource,
double use_rate,
base::ListValue* referral_list) {
// Find the motivation if it is already used.
base::ListValue* motivation_list = FindSerializationMotivation(motivation,
referral_list);
if (!motivation_list) {
// This is the first mention of this motivation, so build a list.
motivation_list = new base::ListValue;
motivation_list->Append(new base::StringValue(motivation.spec()));
// Provide empty subresource list.
motivation_list->Append(new base::ListValue());
// ...and make it part of the serialized referral_list.
referral_list->Append(motivation_list);
}
base::ListValue* subresource_list(NULL);
// 0 == url; 1 == subresource_list.
EXPECT_TRUE(motivation_list->GetList(1, &subresource_list));
// We won't bother to check for the subresource being there already. Worst
// case, during deserialization, the latency value we supply plus the
// existing value(s) will be added to the referrer.
subresource_list->Append(new base::StringValue(subresource.spec()));
subresource_list->Append(new base::FundamentalValue(use_rate));
}
// For a given motivation, and subresource, find what latency is currently
// listed. This assume a well formed serialization, which has at most one such
// entry for any pair of names. If no such pair is found, then return false.
// Data is written into use_rate arguments.
static bool GetDataFromSerialization(const GURL& motivation,
const GURL& subresource,
const base::ListValue& referral_list,
double* use_rate) {
const base::ListValue* motivation_list =
FindSerializationMotivation(motivation, &referral_list);
if (!motivation_list)
return false;
const base::ListValue* subresource_list;
EXPECT_TRUE(motivation_list->GetList(1, &subresource_list));
for (size_t i = 0; i < subresource_list->GetSize();) {
std::string url_spec;
EXPECT_TRUE(subresource_list->GetString(i++, &url_spec));
EXPECT_TRUE(subresource_list->GetDouble(i++, use_rate));
if (subresource == GURL(url_spec)) {
return true;
}
}
return false;
}
//------------------------------------------------------------------------------
// Make sure nil referral lists really have no entries, and no latency listed.
TEST_F(PredictorTest, ReferrerSerializationNilTest) {
Predictor predictor(true);
predictor.SetHostResolver(host_resolver_.get());
scoped_ptr<base::ListValue> referral_list(NewEmptySerializationList());
predictor.SerializeReferrers(referral_list.get());
EXPECT_EQ(1U, referral_list->GetSize());
EXPECT_FALSE(GetDataFromSerialization(
GURL("http://a.com:79"), GURL("http://b.com:78"),
*referral_list.get(), NULL));
predictor.Shutdown();
}
// Make sure that when a serialization list includes a value, that it can be
// deserialized into the database, and can be extracted back out via
// serialization without being changed.
TEST_F(PredictorTest, ReferrerSerializationSingleReferrerTest) {
Predictor predictor(true);
predictor.SetHostResolver(host_resolver_.get());
const GURL motivation_url("http://www.google.com:91");
const GURL subresource_url("http://icons.google.com:90");
const double kUseRate = 23.4;
scoped_ptr<base::ListValue> referral_list(NewEmptySerializationList());
AddToSerializedList(motivation_url, subresource_url,
kUseRate, referral_list.get());
predictor.DeserializeReferrers(*referral_list.get());
base::ListValue recovered_referral_list;
predictor.SerializeReferrers(&recovered_referral_list);
EXPECT_EQ(2U, recovered_referral_list.GetSize());
double rate;
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, subresource_url, recovered_referral_list, &rate));
EXPECT_EQ(rate, kUseRate);
predictor.Shutdown();
}
// Check that GetHtmlReferrerLists() doesn't crash when given duplicated
// domains for referring URL, and that it sorts the results in the
// correct order.
TEST_F(PredictorTest, GetHtmlReferrerLists) {
Predictor predictor(true);
predictor.SetHostResolver(host_resolver_.get());
const double kUseRate = 23.4;
scoped_ptr<base::ListValue> referral_list(NewEmptySerializationList());
AddToSerializedList(
GURL("http://d.google.com/x1"),
GURL("http://foo.com/"),
kUseRate, referral_list.get());
// Duplicated hostname (d.google.com). This should not cause any crashes
// (i.e. crbug.com/116345)
AddToSerializedList(
GURL("http://d.google.com/x2"),
GURL("http://foo.com/"),
kUseRate, referral_list.get());
AddToSerializedList(
GURL("http://a.yahoo.com/y"),
GURL("http://foo1.com/"),
kUseRate, referral_list.get());
AddToSerializedList(
GURL("http://b.google.com/x3"),
GURL("http://foo2.com/"),
kUseRate, referral_list.get());
AddToSerializedList(
GURL("http://d.yahoo.com/x5"),
GURL("http://i.like.turtles/"),
kUseRate, referral_list.get());
AddToSerializedList(
GURL("http://c.yahoo.com/x4"),
GURL("http://foo3.com/"),
kUseRate, referral_list.get());
predictor.DeserializeReferrers(*referral_list.get());
std::string html;
predictor.GetHtmlReferrerLists(&html);
// The lexicographic sorting of hostnames would be:
// a.yahoo.com
// b.google.com
// c.yahoo.com
// d.google.com
// d.yahoo.com
//
// However we expect to sort them by domain in the output:
// b.google.com
// d.google.com
// a.yahoo.com
// c.yahoo.com
// d.yahoo.com
size_t pos[] = {
html.find("<td rowspan=1>http://b.google.com/x3"),
html.find("<td rowspan=1>http://d.google.com/x1"),
html.find("<td rowspan=1>http://d.google.com/x2"),
html.find("<td rowspan=1>http://a.yahoo.com/y"),
html.find("<td rowspan=1>http://c.yahoo.com/x4"),
html.find("<td rowspan=1>http://d.yahoo.com/x5"),
};
// Make sure things appeared in the expected order.
for (size_t i = 1; i < arraysize(pos); ++i) {
EXPECT_LT(pos[i - 1], pos[i]) << "Mismatch for pos[" << i << "]";
}
predictor.Shutdown();
}
// Verify that two floats are within 1% of each other in value.
#define EXPECT_SIMILAR(a, b) do { \
double espilon_ratio = 1.01; \
if ((a) < 0.) \
espilon_ratio = 1 / espilon_ratio; \
EXPECT_LT(a, espilon_ratio * (b)); \
EXPECT_GT((a) * espilon_ratio, b); \
} while (0)
// Make sure the Trim() functionality works as expected.
TEST_F(PredictorTest, ReferrerSerializationTrimTest) {
Predictor predictor(true);
predictor.SetHostResolver(host_resolver_.get());
GURL motivation_url("http://www.google.com:110");
GURL icon_subresource_url("http://icons.google.com:111");
const double kRateIcon = 16.0 * Predictor::kDiscardableExpectedValue;
GURL img_subresource_url("http://img.google.com:118");
const double kRateImg = 8.0 * Predictor::kDiscardableExpectedValue;
scoped_ptr<base::ListValue> referral_list(NewEmptySerializationList());
AddToSerializedList(
motivation_url, icon_subresource_url, kRateIcon, referral_list.get());
AddToSerializedList(
motivation_url, img_subresource_url, kRateImg, referral_list.get());
predictor.DeserializeReferrers(*referral_list.get());
base::ListValue recovered_referral_list;
predictor.SerializeReferrers(&recovered_referral_list);
EXPECT_EQ(2U, recovered_referral_list.GetSize());
double rate;
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, icon_subresource_url, recovered_referral_list,
&rate));
EXPECT_SIMILAR(rate, kRateIcon);
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, img_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateImg);
// Each time we Trim 24 times, the user_rate figures should reduce by a factor
// of two, until they are small, and then a trim will delete the whole entry.
for (int i = 0; i < 24; ++i)
predictor.TrimReferrersNow();
predictor.SerializeReferrers(&recovered_referral_list);
EXPECT_EQ(2U, recovered_referral_list.GetSize());
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, icon_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateIcon / 2);
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, img_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateImg / 2);
for (int i = 0; i < 24; ++i)
predictor.TrimReferrersNow();
predictor.SerializeReferrers(&recovered_referral_list);
EXPECT_EQ(2U, recovered_referral_list.GetSize());
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, icon_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateIcon / 4);
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, img_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateImg / 4);
for (int i = 0; i < 24; ++i)
predictor.TrimReferrersNow();
predictor.SerializeReferrers(&recovered_referral_list);
EXPECT_EQ(2U, recovered_referral_list.GetSize());
EXPECT_TRUE(GetDataFromSerialization(
motivation_url, icon_subresource_url, recovered_referral_list, &rate));
EXPECT_SIMILAR(rate, kRateIcon / 8);
// Img is below threshold, and so it gets deleted.
EXPECT_FALSE(GetDataFromSerialization(
motivation_url, img_subresource_url, recovered_referral_list, &rate));
for (int i = 0; i < 24; ++i)
predictor.TrimReferrersNow();
predictor.SerializeReferrers(&recovered_referral_list);
// Icon is also trimmed away, so entire set gets discarded.
EXPECT_EQ(1U, recovered_referral_list.GetSize());
EXPECT_FALSE(GetDataFromSerialization(
motivation_url, icon_subresource_url, recovered_referral_list, &rate));
EXPECT_FALSE(GetDataFromSerialization(
motivation_url, img_subresource_url, recovered_referral_list, &rate));
predictor.Shutdown();
}
TEST_F(PredictorTest, PriorityQueuePushPopTest) {
Predictor::HostNameQueue queue;
GURL first("http://first:80"), second("http://second:90");
// First check high priority queue FIFO functionality.
EXPECT_TRUE(queue.IsEmpty());
queue.Push(first, UrlInfo::LEARNED_REFERAL_MOTIVATED);
EXPECT_FALSE(queue.IsEmpty());
queue.Push(second, UrlInfo::MOUSE_OVER_MOTIVATED);
EXPECT_FALSE(queue.IsEmpty());
EXPECT_EQ(queue.Pop(), first);
EXPECT_FALSE(queue.IsEmpty());
EXPECT_EQ(queue.Pop(), second);
EXPECT_TRUE(queue.IsEmpty());
// Then check low priority queue FIFO functionality.
queue.Push(first, UrlInfo::PAGE_SCAN_MOTIVATED);
EXPECT_FALSE(queue.IsEmpty());
queue.Push(second, UrlInfo::OMNIBOX_MOTIVATED);
EXPECT_FALSE(queue.IsEmpty());
EXPECT_EQ(queue.Pop(), first);
EXPECT_FALSE(queue.IsEmpty());
EXPECT_EQ(queue.Pop(), second);
EXPECT_TRUE(queue.IsEmpty());
}
TEST_F(PredictorTest, PriorityQueueReorderTest) {
Predictor::HostNameQueue queue;
// Push all the low priority items.
GURL low1("http://low1:80"),
low2("http://low2:80"),
low3("http://low3:443"),
low4("http://low4:80"),
low5("http://low5:80"),
hi1("http://hi1:80"),
hi2("http://hi2:80"),
hi3("http://hi3:80");
EXPECT_TRUE(queue.IsEmpty());
queue.Push(low1, UrlInfo::PAGE_SCAN_MOTIVATED);
queue.Push(low2, UrlInfo::UNIT_TEST_MOTIVATED);
queue.Push(low3, UrlInfo::LINKED_MAX_MOTIVATED);
queue.Push(low4, UrlInfo::OMNIBOX_MOTIVATED);
queue.Push(low5, UrlInfo::STARTUP_LIST_MOTIVATED);
queue.Push(low4, UrlInfo::OMNIBOX_MOTIVATED);
// Push all the high prority items
queue.Push(hi1, UrlInfo::LEARNED_REFERAL_MOTIVATED);
queue.Push(hi2, UrlInfo::STATIC_REFERAL_MOTIVATED);
queue.Push(hi3, UrlInfo::MOUSE_OVER_MOTIVATED);
// Check that high priority stuff comes out first, and in FIFO order.
EXPECT_EQ(queue.Pop(), hi1);
EXPECT_EQ(queue.Pop(), hi2);
EXPECT_EQ(queue.Pop(), hi3);
// ...and then low priority strings.
EXPECT_EQ(queue.Pop(), low1);
EXPECT_EQ(queue.Pop(), low2);
EXPECT_EQ(queue.Pop(), low3);
EXPECT_EQ(queue.Pop(), low4);
EXPECT_EQ(queue.Pop(), low5);
EXPECT_EQ(queue.Pop(), low4);
EXPECT_TRUE(queue.IsEmpty());
}
TEST_F(PredictorTest, CanonicalizeUrl) {
// Base case, only handles HTTP and HTTPS.
EXPECT_EQ(GURL(), Predictor::CanonicalizeUrl(GURL("ftp://anything")));
// Remove path testing.
GURL long_url("http://host:999/path?query=value");
EXPECT_EQ(Predictor::CanonicalizeUrl(long_url), long_url.GetWithEmptyPath());
// Default port cannoncalization.
GURL implied_port("http://test");
GURL explicit_port("http://test:80");
EXPECT_EQ(Predictor::CanonicalizeUrl(implied_port),
Predictor::CanonicalizeUrl(explicit_port));
// Port is still maintained.
GURL port_80("http://test:80");
GURL port_90("http://test:90");
EXPECT_NE(Predictor::CanonicalizeUrl(port_80),
Predictor::CanonicalizeUrl(port_90));
// Host is still maintained.
GURL host_1("http://test_1");
GURL host_2("http://test_2");
EXPECT_NE(Predictor::CanonicalizeUrl(host_1),
Predictor::CanonicalizeUrl(host_2));
// Scheme is maintained (mismatch identified).
GURL http("http://test");
GURL https("https://test");
EXPECT_NE(Predictor::CanonicalizeUrl(http),
Predictor::CanonicalizeUrl(https));
// Https works fine.
GURL long_https("https://host:999/path?query=value");
EXPECT_EQ(Predictor::CanonicalizeUrl(long_https),
long_https.GetWithEmptyPath());
}
TEST_F(PredictorTest, DiscardPredictorResults) {
Predictor predictor(true);
predictor.SetHostResolver(host_resolver_.get());
base::ListValue referral_list;
predictor.SerializeReferrers(&referral_list);
EXPECT_EQ(1U, referral_list.GetSize());
GURL host_1("http://test_1");
GURL host_2("http://test_2");
predictor.LearnFromNavigation(host_1, host_2);
predictor.SerializeReferrers(&referral_list);
EXPECT_EQ(2U, referral_list.GetSize());
predictor.DiscardAllResults();
predictor.SerializeReferrers(&referral_list);
EXPECT_EQ(1U, referral_list.GetSize());
predictor.Shutdown();
}
#if defined(OS_ANDROID) || defined(OS_IOS)
// Tests for the predictor with a proxy advisor
class TestProxyAdvisor : public ProxyAdvisor {
public:
TestProxyAdvisor()
: ProxyAdvisor(NULL, NULL),
would_proxy_(false),
advise_count_(0),
would_proxy_count_(0) {
}
virtual ~TestProxyAdvisor() {}
virtual void Advise(const GURL& url,
UrlInfo::ResolutionMotivation motivation,
bool is_preconnect) OVERRIDE {
++advise_count_;
}
virtual bool WouldProxyURL(const GURL& url) OVERRIDE {
++would_proxy_count_;
return would_proxy_;
}
bool would_proxy_;
int advise_count_;
int would_proxy_count_;
};
TEST_F(PredictorTest, SingleLookupTestWithDisabledAdvisor) {
Predictor testing_master(true);
TestProxyAdvisor* advisor = new TestProxyAdvisor();
testing_master.SetHostResolver(host_resolver_.get());
testing_master.proxy_advisor_.reset(advisor);
GURL goog("http://www.google.com:80");
advisor->would_proxy_ = false;
UrlList names;
names.push_back(goog);
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
WaitForResolution(&testing_master, names);
EXPECT_TRUE(testing_master.WasFound(goog));
EXPECT_EQ(advisor->would_proxy_count_, 1);
EXPECT_EQ(advisor->advise_count_, 1);
base::MessageLoop::current()->RunUntilIdle();
testing_master.Shutdown();
}
TEST_F(PredictorTest, SingleLookupTestWithEnabledAdvisor) {
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver_.get());
TestProxyAdvisor* advisor = new TestProxyAdvisor();
testing_master.proxy_advisor_.reset(advisor);
GURL goog("http://www.google.com:80");
advisor->would_proxy_ = true;
UrlList names;
names.push_back(goog);
testing_master.ResolveList(names, UrlInfo::PAGE_SCAN_MOTIVATED);
// Attempt to resolve a few times.
WaitForResolutionWithLimit(&testing_master, names, 10);
// Because the advisor indicated that the url would be proxied,
// no resolution should have occurred.
EXPECT_FALSE(testing_master.WasFound(goog));
EXPECT_EQ(advisor->would_proxy_count_, 1);
EXPECT_EQ(advisor->advise_count_, 1);
base::MessageLoop::current()->RunUntilIdle();
testing_master.Shutdown();
}
TEST_F(PredictorTest, TestSimplePreconnectAdvisor) {
Predictor testing_master(true);
testing_master.SetHostResolver(host_resolver_.get());
TestProxyAdvisor* advisor = new TestProxyAdvisor();
testing_master.proxy_advisor_.reset(advisor);
GURL goog("http://www.google.com:80");
testing_master.PreconnectUrl(goog, goog, UrlInfo::OMNIBOX_MOTIVATED, 2);
EXPECT_EQ(advisor->would_proxy_count_, 0);
EXPECT_EQ(advisor->advise_count_, 1);
testing_master.Shutdown();
}
#endif // defined(OS_ANDROID) || defined(OS_IOS)
} // namespace chrome_browser_net
|
; lzo1x_f2.asm -- lzo1x_decompress_asm_fast_safe
;
; This file is part of the LZO real-time data compression library.
;
; Copyright (C) 2008 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2007 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2006 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer
; Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer
; All Rights Reserved.
;
; The LZO library is free software; you can redistribute it and/or
; modify it under the terms of the GNU General Public License as
; published by the Free Software Foundation; either version 2 of
; the License, or (at your option) any later version.
;
; The LZO library is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with the LZO library; see the file COPYING.
; If not, write to the Free Software Foundation, Inc.,
; 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
;
; Markus F.X.J. Oberhumer
; <markus@oberhumer.com>
; http://www.oberhumer.com/opensource/lzo/
;
; /***** DO NOT EDIT - GENERATED AUTOMATICALLY *****/
include asminit.def
public _lzo1x_decompress_asm_fast_safe
_lzo1x_decompress_asm_fast_safe:
db 85,87,86,83,81,82,131,236,12,252,139,116,36,40,139,124
db 36,48,189,3,0,0,0,141,70,253,3,68,36,44,137,68
db 36,4,137,248,139,84,36,52,3,2,137,4,36,49,192,49
db 219,172,60,17,118,55,44,14,235,62,5,255,0,0,0,141
db 84,6,18,57,84,36,4,15,130,78,2,0,0,138,30,70
db 8,219,116,230,141,68,24,21,235,30,141,182,0,0,0,0
db 57,116,36,4,15,130,49,2,0,0,138,6,70,60,16,115
db 119,8,192,116,216,131,192,6,141,84,7,253,57,20,36,15
db 130,29,2,0,0,141,84,6,253,57,84,36,4,15,130,8
db 2,0,0,137,193,49,232,193,233,2,33,232,139,22,131,198
db 4,137,23,131,199,4,73,117,243,41,198,41,199,138,6,70
db 60,16,115,52,141,87,3,57,20,36,15,130,226,1,0,0
db 193,232,2,138,30,141,151,255,247,255,255,141,4,152,70,41
db 194,59,84,36,48,15,130,206,1,0,0,139,10,137,15,1
db 239,233,151,0,0,0,137,246,60,64,114,68,137,193,193,232
db 2,141,87,255,131,224,7,138,30,193,233,5,141,4,216,70
db 41,194,131,193,4,57,232,115,73,233,170,0,0,0,5,255
db 0,0,0,141,86,3,57,84,36,4,15,130,123,1,0,0
db 138,30,70,8,219,116,231,141,76,24,36,49,192,235,17,144
db 60,32,15,130,200,0,0,0,131,224,31,116,227,141,72,5
db 102,139,6,141,87,255,193,232,2,131,198,2,41,194,57,232
db 114,102,59,84,36,48,15,130,77,1,0,0,141,68,15,253
db 193,233,2,57,4,36,15,130,54,1,0,0,139,26,131,194
db 4,137,31,131,199,4,73,117,243,137,199,49,219,138,70,254
db 33,232,15,132,216,254,255,255,141,20,7,57,20,36,15,130
db 14,1,0,0,141,20,6,57,84,36,4,15,130,250,0,0
db 0,139,22,1,198,137,23,1,199,138,6,70,233,55,255,255
db 255,141,180,38,0,0,0,0,59,84,36,48,15,130,231,0
db 0,0,141,68,15,253,57,4,36,15,130,211,0,0,0,135
db 214,41,233,243,164,137,214,235,164,129,193,255,0,0,0,141
db 86,3,57,84,36,4,15,130,175,0,0,0,138,30,70,8
db 219,116,230,141,76,11,12,235,27,141,180,38,0,0,0,0
db 60,16,114,44,137,193,131,224,8,193,224,13,131,225,7,116
db 219,131,193,5,102,139,6,131,198,2,141,151,0,192,255,255
db 193,232,2,116,57,41,194,233,38,255,255,255,141,116,38,0
db 141,87,2,57,20,36,114,106,193,232,2,138,30,141,87,255
db 141,4,152,70,41,194,59,84,36,48,114,93,138,2,136,7
db 138,90,1,136,95,1,131,199,2,233,31,255,255,255,131,249
db 6,15,149,192,59,60,36,119,57,139,84,36,40,3,84,36
db 44,57,214,119,38,114,29,43,124,36,48,139,84,36,52,137
db 58,247,216,131,196,12,90,89,91,94,95,93,195,184,1,0
db 0,0,235,227,184,8,0,0,0,235,220,184,4,0,0,0
db 235,213,184,5,0,0,0,235,206,184,6,0,0,0,235,199
end
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r13
push %r14
push %rbp
push %rcx
push %rdi
push %rdx
push %rsi
lea addresses_UC_ht+0x888e, %rsi
lea addresses_UC_ht+0x37ef, %rdi
nop
inc %r14
mov $100, %rcx
rep movsw
nop
nop
and $28437, %rdx
lea addresses_D_ht+0x134c5, %r10
nop
sub %rbp, %rbp
mov (%r10), %r14
nop
nop
nop
nop
nop
cmp $46623, %rcx
lea addresses_A_ht+0x1e86b, %r14
nop
xor $29832, %rsi
mov $0x6162636465666768, %rcx
movq %rcx, (%r14)
nop
nop
nop
cmp $41618, %rbp
lea addresses_normal_ht+0x9f23, %rsi
lea addresses_UC_ht+0x24cb, %rdi
nop
nop
nop
add %r13, %r13
mov $45, %rcx
rep movsw
nop
nop
nop
nop
nop
inc %rbp
lea addresses_A_ht+0x1406b, %r14
inc %rdi
mov $0x6162636465666768, %r10
movq %r10, %xmm1
movups %xmm1, (%r14)
nop
add $12580, %rdx
lea addresses_normal_ht+0x8b55, %r10
nop
cmp %rdx, %rdx
mov $0x6162636465666768, %rsi
movq %rsi, (%r10)
nop
nop
inc %rcx
lea addresses_normal_ht+0x1d96b, %rsi
lea addresses_D_ht+0x1bc6b, %rdi
cmp %rdx, %rdx
mov $30, %rcx
rep movsw
nop
nop
nop
add %rbp, %rbp
lea addresses_A_ht+0x1162b, %rsi
lea addresses_WC_ht+0x355b, %rdi
clflush (%rdi)
nop
nop
inc %rdx
mov $121, %rcx
rep movsq
sub $3561, %r14
lea addresses_UC_ht+0x10ceb, %rsi
lea addresses_WT_ht+0x116b, %rdi
sub %r14, %r14
mov $78, %rcx
rep movsw
nop
nop
nop
nop
nop
xor %rsi, %rsi
lea addresses_WT_ht+0x1b790, %rdi
clflush (%rdi)
and $49943, %rcx
movb $0x61, (%rdi)
nop
nop
nop
nop
inc %r10
lea addresses_D_ht+0x71eb, %r10
xor $34490, %rsi
movw $0x6162, (%r10)
nop
nop
xor %rdx, %rdx
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbp
pop %r14
pop %r13
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r10
push %r11
push %r12
push %r13
push %rbp
push %rdi
push %rdx
// Load
lea addresses_D+0xb86b, %rbp
nop
nop
cmp %r13, %r13
mov (%rbp), %r11w
nop
nop
and %r13, %r13
// Store
lea addresses_WC+0x15831, %r10
nop
nop
nop
nop
nop
and %r12, %r12
movl $0x51525354, (%r10)
nop
nop
nop
nop
nop
add %r11, %r11
// Load
lea addresses_WT+0x1796b, %rdi
nop
nop
nop
add $64298, %r12
mov (%rdi), %r11
add $38568, %r13
// Store
lea addresses_WT+0x1a8ab, %rbp
clflush (%rbp)
and %rdx, %rdx
mov $0x5152535455565758, %r10
movq %r10, %xmm3
vmovups %ymm3, (%rbp)
nop
nop
xor $41254, %r12
// Load
lea addresses_US+0x4183, %rdi
nop
nop
nop
nop
sub $26569, %r12
movb (%rdi), %r13b
nop
nop
nop
nop
nop
xor %r11, %r11
// Store
lea addresses_PSE+0xd6b, %rdx
cmp $26522, %rbp
mov $0x5152535455565758, %r12
movq %r12, (%rdx)
nop
nop
nop
sub %rdx, %rdx
// Faulty Load
lea addresses_PSE+0x2c6b, %r11
nop
cmp $44352, %r12
vmovups (%r11), %ymm7
vextracti128 $0, %ymm7, %xmm7
vpextrq $0, %xmm7, %r10
lea oracles, %rdx
and $0xff, %r10
shlq $12, %r10
mov (%rdx,%r10,1), %r10
pop %rdx
pop %rdi
pop %rbp
pop %r13
pop %r12
pop %r11
pop %r10
ret
/*
<gen_faulty_load>
[REF]
{'OP': 'LOAD', 'src': {'size': 4, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 2, 'NT': False, 'type': 'addresses_D', 'same': False, 'AVXalign': False, 'congruent': 10}}
{'OP': 'STOR', 'dst': {'size': 4, 'NT': False, 'type': 'addresses_WC', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 32, 'NT': False, 'type': 'addresses_WT', 'same': False, 'AVXalign': False, 'congruent': 3}}
{'OP': 'LOAD', 'src': {'size': 1, 'NT': False, 'type': 'addresses_US', 'same': False, 'AVXalign': False, 'congruent': 2}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_PSE', 'same': False, 'AVXalign': True, 'congruent': 6}}
[Faulty Load]
{'OP': 'LOAD', 'src': {'size': 32, 'NT': False, 'type': 'addresses_PSE', 'same': True, 'AVXalign': False, 'congruent': 0}}
<gen_prepare_buffer>
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 0}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 1}}
{'OP': 'LOAD', 'src': {'size': 8, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_normal_ht', 'congruent': 3}, 'dst': {'same': False, 'type': 'addresses_UC_ht', 'congruent': 5}}
{'OP': 'STOR', 'dst': {'size': 16, 'NT': False, 'type': 'addresses_A_ht', 'same': False, 'AVXalign': False, 'congruent': 9}}
{'OP': 'STOR', 'dst': {'size': 8, 'NT': True, 'type': 'addresses_normal_ht', 'same': False, 'AVXalign': False, 'congruent': 1}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_normal_ht', 'congruent': 1}, 'dst': {'same': False, 'type': 'addresses_D_ht', 'congruent': 11}}
{'OP': 'REPM', 'src': {'same': False, 'type': 'addresses_A_ht', 'congruent': 5}, 'dst': {'same': False, 'type': 'addresses_WC_ht', 'congruent': 2}}
{'OP': 'REPM', 'src': {'same': True, 'type': 'addresses_UC_ht', 'congruent': 6}, 'dst': {'same': False, 'type': 'addresses_WT_ht', 'congruent': 8}}
{'OP': 'STOR', 'dst': {'size': 1, 'NT': False, 'type': 'addresses_WT_ht', 'same': True, 'AVXalign': False, 'congruent': 0}}
{'OP': 'STOR', 'dst': {'size': 2, 'NT': False, 'type': 'addresses_D_ht', 'same': False, 'AVXalign': False, 'congruent': 7}}
{'33': 21829}
33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33 33
*/
|
; A215555: a(n) = binomial(11*n,n)*(9*n+1)/(10*n+1).
; Submitted by Jon Maiga
; 1,10,209,4928,122507,3137706,81921840,2167714560,57928578191,1559830082888,42254306265171,1150225193717600,31437550449182800,862165662720962754,23713320186494219820,653855026849948319616,18068367354658442882775,500254126810079793897130,13874014768135937081198532,385366487642611604295886720,10718618228363223393729533481,298496504986103083359088068900,8321963034534497597228601500120,232249856355750553612583553662400,6487700191036189648732427199181200,181383930546937002627848171815484736
mov $2,11
mul $2,$0
mov $1,$2
bin $1,$0
sub $0,1
bin $2,$0
sub $1,$2
mov $0,$1
|
; Inicialização para VM
leaw $Main.main, %A
jmp
nop
; 0 - Declarando função mult
mult:
leaw $0,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $0,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 1 - PUSH constant 0
leaw $0,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 2 - POP local 0
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
leaw $0,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%D
leaw $R15,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%A
movw (%A),%D
leaw $R15,%A
movw (%A),%A
movw %D,(%A)
; 3 - PUSH argument 1
leaw $1,%A
movw %A,%D
leaw $ARG,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 4 - POP local 1
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
leaw $1,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%D
leaw $R15,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%A
movw (%A),%D
leaw $R15,%A
movw (%A),%A
movw %D,(%A)
; Label (marcador)
mult.mult.loop:
; 5 - PUSH constant 0
leaw $0,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 6 - PUSH local 1
leaw $1,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 7 - EQ
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw (%A),%A
movw (%A),%D
leaw $SP,%A
subw (%A),$1,%A
subw (%A),%D,%D
leaw $EQmult0,%A
je %D
nop
leaw $SP,%A
subw (%A),$1,%A
movw $0,(%A)
leaw $EQ2mult0,%A
jmp
nop
EQmult0:
leaw $SP,%A
subw (%A),$1,%A
movw $-1,(%A)
EQ2mult0:
; 8 - Goto Condicional
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw (%A),%A
movw (%A),%D
leaw $mult.mult.end,%A
jne %D
nop
; 9 - PUSH local 0
leaw $0,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 10 - PUSH argument 0
leaw $0,%A
movw %A,%D
leaw $ARG,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 11 - ADD
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw (%A),%A
movw (%A),%D
leaw $SP,%A
subw (%A),$1,%A
addw (%A),%D,%D
movw %D,(%A)
; 12 - POP local 0
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
leaw $0,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%D
leaw $R15,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%A
movw (%A),%D
leaw $R15,%A
movw (%A),%A
movw %D,(%A)
; 13 - PUSH local 1
leaw $1,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 14 - PUSH constant 1
leaw $1,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 15 - SUB
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw (%A),%A
movw (%A),%D
leaw $SP,%A
subw (%A),$1,%A
subw (%A),%D,%D
movw %D,(%A)
; 16 - POP local 1
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
leaw $1,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%D
leaw $R15,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%A
movw (%A),%D
leaw $R15,%A
movw (%A),%A
movw %D,(%A)
; 17 - Goto Incondicional
leaw $mult.mult.loop,%A
jmp
nop
; Label (marcador)
mult.mult.end:
; 18 - PUSH local 0
leaw $0,%A
movw %A,%D
leaw $LCL,%A
addw (%A),%D,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 19 - Retorno de função
; Retorno de função
leaw $LCL,%A
movw (%A),%D
leaw $R13,%A
movw %D,(%A)
leaw $5,%A
subw %D,%A,%A
movw (%A),%D
leaw $R14,%A
movw %D,(%A)
leaw $ARG,%A
movw (%A),%D
leaw $R15,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw %D,%A
movw (%A),%D
leaw $R15,%A
movw (%A),%A
movw %D,(%A)
leaw $ARG,%A
movw (%A),%D
leaw $SP,%A
addw %D,$1,(%A)
leaw $R13,%A
subw (%A),$1,%D
movw %D,(%A)
movw %D,%A
movw (%A),%D
leaw $THAT,%A
movw %D,(%A)
leaw $R13,%A
subw (%A),$1,%D
movw %D,(%A)
movw %D,%A
movw (%A),%D
leaw $THIS,%A
movw %D,(%A)
leaw $R13,%A
subw (%A),$1,%D
movw %D,(%A)
movw %D,%A
movw (%A),%D
leaw $ARG,%A
movw %D,(%A)
leaw $R13,%A
subw (%A),$1,%D
movw %D,(%A)
movw %D,%A
movw (%A),%D
leaw $LCL,%A
movw %D,(%A)
leaw $R14,%A
movw (%A),%A
jmp
nop
; End
; 20 - Declarando função Main.main
Main.main:
; 21 - PUSH constant 7
leaw $7,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 22 - PUSH constant 2
leaw $2,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 23 - ADD
leaw $SP,%A
movw (%A),%D
decw %D
movw %D,(%A)
movw (%A),%A
movw (%A),%D
leaw $SP,%A
subw (%A),$1,%A
addw (%A),%D,%D
movw %D,(%A)
; 24 - PUSH constant 3
leaw $3,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
; 25 - chamada de funcao mult
leaw $mult.ret.1,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $LCL,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $ARG,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $THIS,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $THAT,%A
movw (%A),%D
leaw $SP,%A
movw (%A),%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
incw %D
movw %D,(%A)
leaw $7,%A
movw %A,%D
leaw $SP,%A
movw (%A),%A
subw %A,%D,%D
leaw $ARG,%A
movw %D,(%A)
leaw $SP,%A
movw (%A),%D
leaw $LCL,%A
movw %D,(%A)
leaw $mult,%A
jmp
nop
mult.ret.1:
; End
|
/**
* Copyright 2019-2021 Huawei Technologies Co., Ltd
*
* 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 "minddata/dataset/util/cond_var.h"
#include "minddata/dataset/util/services.h"
#include "minddata/dataset/util/task_manager.h"
namespace mindspore {
namespace dataset {
CondVar::CondVar() : svc_(nullptr), my_name_(Services::GetUniqueID()) {}
Status CondVar::Wait(std::unique_lock<std::mutex> *lck, const std::function<bool()> &pred) {
try {
if (svc_ != nullptr) {
// If this cv registers with a global resource tracking, then wait unconditionally.
auto f = [this, &pred]() -> bool { return (pred() || this->Interrupted()); };
cv_.wait(*lck, f);
// If we are interrupted, override the return value if this is the master thread.
// Master thread is being interrupted mostly because of some thread is reporting error.
RETURN_IF_NOT_OK(Task::OverrideInterruptRc(this->GetInterruptStatus()));
} else {
// Otherwise we wake up once a while to check for interrupt (for this thread).
auto f = [&pred]() -> bool { return (pred() || this_thread::is_interrupted()); };
while (!f()) {
(void)cv_.wait_for(*lck, std::chrono::milliseconds(1));
}
RETURN_IF_INTERRUPTED();
}
} catch (const std::exception &e) {
RETURN_STATUS_UNEXPECTED(e.what());
}
return Status::OK();
}
Status CondVar::WaitFor(std::unique_lock<std::mutex> *lck, int64_t duration) {
try {
if (svc_ != nullptr) {
// If this cv registers with a global resource tracking, then wait unconditionally.
auto f = [this]() -> bool { return this->Interrupted(); };
(void)cv_.wait_for(*lck, std::chrono::milliseconds(duration), f);
// If we are interrupted, override the return value if this is the master thread.
// Master thread is being interrupted mostly because of some thread is reporting error.
RETURN_IF_NOT_OK(Task::OverrideInterruptRc(this->GetInterruptStatus()));
} else {
// Otherwise we wake up once a while to check for interrupt (for this thread).
auto f = []() -> bool { return this_thread::is_interrupted(); };
int64_t ctr = 0;
while (!f() && ctr++ < duration) {
(void)cv_.wait_for(*lck, std::chrono::milliseconds(1), f);
}
RETURN_IF_INTERRUPTED();
}
} catch (const std::exception &e) {
RETURN_STATUS_UNEXPECTED(e.what());
}
return Status::OK();
}
CondVar::~CondVar() noexcept {
if (svc_ != nullptr) {
(void)svc_->Deregister(my_name_);
svc_ = nullptr;
}
}
void CondVar::NotifyOne() noexcept { cv_.notify_one(); }
void CondVar::NotifyAll() noexcept { cv_.notify_all(); }
Status CondVar::Register(std::shared_ptr<IntrpService> svc) {
Status rc = svc->Register(&my_name_, this);
if (rc.IsOk()) {
svc_ = svc;
}
return rc;
}
void CondVar::Interrupt() {
IntrpResource::Interrupt();
cv_.notify_all();
}
std::string CondVar::my_name() const { return my_name_; }
Status CondVar::Deregister() {
if (svc_) {
Status rc = svc_->Deregister(my_name_);
svc_ = nullptr;
return rc;
}
return Status::OK();
}
} // namespace dataset
} // namespace mindspore
|
#ifndef __SCENE_H__
#define __SCENE_H__
#include "light.hpp"
#include "Objects.hpp"
class Scene
{
public:
Scene(std::vector<float> cam_param, std::vector<float> light_param, std::vector<glm::vec3> floor_param);
void object_init(glm::vec3 position = glm::vec3(0,0,0),
glm::vec3 rotation = glm::vec3(0,0,0),
glm::vec3 scale = glm::vec3(0.5));
void onUpdate(Light::Timestep ts);
void onEvent(Light::Event& e);
void render();
void camResize(float x, float y);
float* getLightPos();
private:
Light::EditorCamera camera;
Cube floor;
Skybox skybox;
glm::vec3 lightPos;
std::vector<Cube> objects;
};
#endif //__SCENE_H__ |
; A166648: Totally multiplicative sequence with a(p) = 8*(p+1) for prime p.
; Submitted by Jon Maiga
; 1,24,32,576,48,768,64,13824,1024,1152,96,18432,112,1536,1536,331776,144,24576,160,27648,2048,2304,192,442368,2304,2688,32768,36864,240,36864,256,7962624,3072,3456,3072,589824,304,3840,3584,663552,336,49152,352,55296,49152,4608,384,10616832,4096,55296,4608,64512,432,786432,4608,884736,5120,5760,480,884736,496,6144,65536,191102976,5376,73728,544,82944,6144,73728,576,14155776,592,7296,73728,92160,6144,86016,640,15925248,1048576,8064,672,1179648,6912,8448,7680,1327104,720,1179648,7168,110592,8192
add $0,1
mov $1,1
mov $2,2
mov $4,1
lpb $0
mul $1,$4
mul $1,2
mov $3,$0
lpb $3
mov $4,$0
mod $4,$2
add $2,1
cmp $4,0
cmp $4,0
sub $3,$4
lpe
div $0,$2
mov $4,$2
mov $5,$2
lpb $5
add $4,3
sub $5,1
lpe
add $4,4
lpe
mov $0,$1
div $0,2
|
section .data
msg1 db'enter the size of array',0ax
len1 equ $-msg1
msg2 db'the average is',0ax
len2 equ $-msg2
msg3 db'count of numbers above average is:',0ax
len3 equ $-msg3
section .bss
num resd 1
size resd 1
temp resb 1
num1 resd 1
count resd 1
array resd 100
counter resd 1
sum resd 1
section .text
global _start:
read_num:
pusha
mov dword[num],0
loop_read:
mov eax,3
mov ebx,0
mov ecx,temp
mov edx,1
int 80h
cmp byte[temp],0Ah
je end_read
mov eax,dword[num]
mov ebx,10
mul ebx
mov bl,byte[temp]
sub bl,30h
mov bh,0
add eax,ebx
mov dword[num],eax
jmp loop_read
end_read:
popa
ret
print_num:
mov byte[count],0
pusha
extract:
cmp dword[num],0
je print
inc byte[count]
mov edx,0
mov eax,dword[num]
mov ebx,10
div ebx
push edx
mov dword[num],eax
jmp extract
print:
cmp byte[count],0
je end_print
dec byte[count]
pop edx
mov byte[temp],dl
add byte[temp],30h
mov eax,4
mov ebx,1
mov ecx,temp
mov edx,1
int 80h
jmp print
end_print:
mov eax,4
mov ebx,1
mov ecx,0Ah
mov edx,1
int 80h
popa
ret
start_arrayread:
pusha
read_loop:
cmp eax,dword[size]
je end_read1
call read_num
mov ecx,dword[num]
mov dword[ebx+4*eax],ecx
inc eax
jmp read_loop
end_read1:
popa
ret
print_array:
pusha
print_loop:
cmp eax,dword[size]
je end_print
mov ecx,dword[ebx+4*eax]
mov dword[num],ecx
call print_num
inc eax
jmp print_loop
jstinc:
inc dword[counter]
inc eax
jmp gear
counting:
pusha
gear:
cmp eax,dword[size]
jg fin
mov ecx,dword[ebx+4*eax]
cmp ecx,dword[sum]
jg jstinc
inc eax
jmp gear
fin:
mov eax,dword[counter]
mov dword[num],eax
call print_num
jmp exit
_start:
mov eax,4
mov ebx,1
mov ecx,msg1
mov edx,len1
int 80h
call read_num
mov eax,dword[num]
mov dword[size],eax
mov ebx,array
mov eax,0
call start_arrayread
;mov ebx,array
;mov eax,0
;call print_array
mov eax,4
mov ebx,1
mov ecx,msg2
mov edx,len2
int 80h
mov ebx,array
mov eax,0
mov dword[sum],0
avg:
cmp eax,dword[size]
je end_avg
mov ecx,dword[ebx+4*eax]
add dword[sum],ecx
inc eax
jmp avg
end_avg:
mov edx,0
mov eax,dword[sum]
mov ebx,dword[size]
div ebx
mov dword[num],eax
mov dword[sum],eax
call print_num
mov eax,4
mov ebx,1
mov ecx,msg3
mov edx,len3
int 80h
mov ebx,array
mov eax,0
mov dword[counter],0
call counting
exit:
mov eax,1
mov ebx,0
int 80h |
//
// Generated by Microsoft (R) HLSL Shader Compiler 9.30.9200.20714
//
//
///
// Buffer Definitions:
//
// cbuffer cb
// {
//
// row_major float4x4 g_matWVP; // Offset: 0 Size: 64
// float2 g_tess_edge_length_scale; // Offset: 64 Size: 8
// int num_triangles; // Offset: 72 Size: 4
// float dummy; // Offset: 76 Size: 4 [unused]
//
// }
//
// Resource bind info for EdgeFactorBufOut
// {
//
// float4 $Element; // Offset: 0 Size: 16
//
// }
//
//
// Resource Bindings:
//
// Name Type Format Dim Slot Elements
// ------------------------------ ---------- ------- ----------- ---- --------
// InputVertices texture float4 buf 0 1
// EdgeFactorBufOut UAV struct r/w 0 1
// cb cbuffer NA NA 0 1
//
//
//
// Input signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// no Input
//
// Output signature:
//
// Name Index Mask Register SysValue Format Used
// -------------------- ----- ------ -------- -------- ------- ------
// no Output
cs_4_0
dcl_globalFlags refactoringAllowed
dcl_constantbuffer cb0[5], immediateIndexed
dcl_resource_buffer (float,float,float,float) t0
dcl_uav_structured u0, 16
dcl_input vThreadID.x
dcl_temps 10
dcl_thread_group 128, 1, 1
ult r0.x, vThreadID.x, cb0[4].z
if_nz r0.x
imul null, r0.x, vThreadID.x, l(3)
ld r0.xyzw, r0.xxxx, t0.xyzw
mul r1.xyzw, r0.yyyy, cb0[1].xyzw
mad r1.xyzw, r0.xxxx, cb0[0].xyzw, r1.xyzw
mad r1.xyzw, r0.zzzz, cb0[2].xyzw, r1.xyzw
mad r0.xyzw, r0.wwww, cb0[3].xyzw, r1.xyzw
imad r1.xy, vThreadID.xxxx, l(3, 3, 0, 0), l(1, 2, 0, 0)
ld r2.xyzw, r1.xxxx, t0.xyzw
mul r3.xyzw, r2.yyyy, cb0[1].xyzw
mad r3.xyzw, r2.xxxx, cb0[0].xyzw, r3.xyzw
mad r3.xyzw, r2.zzzz, cb0[2].xyzw, r3.xyzw
mad r2.xyzw, r2.wwww, cb0[3].xyzw, r3.xyzw
ld r1.xyzw, r1.yyyy, t0.xyzw
mul r3.xyzw, r1.yyyy, cb0[1].xyzw
mad r3.xyzw, r1.xxxx, cb0[0].xyzw, r3.xyzw
mad r3.xyzw, r1.zzzz, cb0[2].xyzw, r3.xyzw
mad r1.xyzw, r1.wwww, cb0[3].xyzw, r3.xyzw
div r0.xyz, r0.xyzx, r0.wwww
div r2.xyz, r2.xyzx, r2.wwww
div r1.xyz, r1.xyzx, r1.wwww
add r3.xyz, r0.xyzx, l(-0.000000, -0.000000, -0.500000, 0.000000)
add r4.xyz, r2.xyzx, l(-0.000000, -0.000000, -0.500000, 0.000000)
add r5.xyz, r1.xyzx, l(-0.000000, -0.000000, -0.500000, 0.000000)
add r6.xyz, -r3.zxyz, r4.zxyz
mul r0.zw, r3.zzzz, r6.zzzy
mad r0.z, r6.x, r3.y, -r0.z
mul r7.xyz, r5.zzxz, r6.zyzz
mad r1.z, r6.x, r5.y, -r7.x
min r1.w, r0.z, r1.z
max r0.z, r0.z, r1.z
dp2 r1.z, |r6.xzxx|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.z, -r1.z, r0.z
and r0.z, r0.z, r1.w
mad r0.w, -r6.x, r3.x, r0.w
mad r1.z, -r6.x, r5.x, r7.y
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r6.xyxx|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.zw, r0.zzzw
or r0.z, r0.w, r0.z
mul r0.w, r4.y, r6.y
mad r0.w, r6.z, r4.x, -r0.w
mad r1.z, -r6.y, r5.y, r7.z
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r6.zyzz|, l(1.020000, 1.020000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.w, r0.w
or r0.z, r0.w, r0.z
if_z r0.z
add r7.xyz, -r4.yzxy, r5.yzxy
mul r8.xyz, r3.zzxz, r7.xzxx
mad r0.z, r7.y, r3.y, -r8.x
mul r1.zw, r5.zzzz, r7.xxxz
mad r0.w, r7.y, r5.y, -r1.z
min r1.z, r0.w, r0.z
max r0.z, r0.w, r0.z
dp2 r0.w, |r7.yxyy|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.z, r1.z, r0.w
lt r0.z, -r0.w, r0.z
and r0.z, r0.z, r1.z
mad r0.w, -r7.y, r3.x, r8.y
mad r1.z, -r7.y, r5.x, r1.w
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r7.yzyy|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.zw, r0.zzzw
or r0.z, r0.w, r0.z
mad r0.w, -r7.z, r3.y, r8.z
mul r1.z, r4.y, r7.z
mad r1.z, r7.x, r4.x, -r1.z
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r7.xzxx|, l(1.020000, 1.020000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.w, r0.w
or r0.z, r0.w, r0.z
if_z r0.z
add r8.xyzw, r3.zyxy, -r5.zyxy
mul r0.zw, r3.zzzz, r8.wwwz
mad r0.z, r8.x, r3.y, -r0.z
mul r9.xyz, r4.zzxz, r8.yzwy
mad r1.z, r8.x, r4.y, -r9.x
min r1.w, r0.z, r1.z
max r0.z, r0.z, r1.z
dp2 r1.z, |r8.xwxx|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.z, -r1.z, r0.z
and r0.z, r0.z, r1.w
mad r0.w, -r8.x, r3.x, r0.w
mad r1.z, -r8.x, r4.x, r9.y
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r8.xzxx|, l(1.020000, 0.520000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.zw, r0.zzzw
or r0.z, r0.w, r0.z
mad r0.w, -r8.z, r4.y, r9.z
mul r1.z, r5.y, r8.z
mad r1.z, r8.w, r5.x, -r1.z
min r1.w, r0.w, r1.z
max r0.w, r0.w, r1.z
dp2 r1.z, |r8.wzww|, l(1.020000, 1.020000, 0.000000, 0.000000)
lt r1.w, r1.w, r1.z
lt r0.w, -r1.z, r0.w
and r0.w, r0.w, r1.w
not r0.w, r0.w
or r0.z, r0.w, r0.z
if_z r0.z
min r8.xyz, r3.xyzx, r4.xyzx
min r8.xyz, r5.xyzx, r8.xyzx
max r4.xyz, r3.xyzx, r4.xyzx
max r4.xyz, r5.xyzx, r4.xyzx
lt r5.xyz, l(1.020000, 1.020000, 0.520000, 0.000000), r8.xyzx
lt r4.xyz, r4.xyzx, l(-1.020000, -1.020000, -0.520000, 0.000000)
or r4.xyz, r4.xyzx, r5.xyzx
or r0.z, r4.y, r4.x
or r0.z, r4.z, r0.z
if_z r0.z
mul r4.xyz, r6.xyzx, r7.xyzx
mad r4.xyz, r6.zxyz, r7.yzxy, -r4.xyzx
dp3 r0.z, r4.xyzx, r3.xyzx
lt r3.xyz, l(0.000000, 0.000000, 0.000000, 0.000000), r4.xyzx
movc r5.xyzw, r3.xxyy, l(-1.020000,1.020000,-1.020000,1.020000), l(1.020000,-1.020000,1.020000,-1.020000)
movc r3.xz, r3.zzzz, l(-0.520000,0,0.520000,0), l(0.520000,0,-0.520000,0)
mov r3.yw, r5.xxxz
dp3 r0.w, r4.zxyz, r3.xywx
add r0.w, -r0.z, r0.w
ge r0.w, l(0.000000), r0.w
mov r3.xy, r5.ywyy
dp3 r1.z, r4.xyzx, r3.xyzx
add r0.z, -r0.z, r1.z
lt r0.z, r0.z, l(0.000000)
ieq r0.z, r0.z, l(0)
and r0.z, r0.z, r0.w
else
mov r0.z, l(0)
endif
else
mov r0.z, l(0)
endif
else
mov r0.z, l(0)
endif
else
mov r0.z, l(0)
endif
add r1.zw, r0.xxxy, -r1.xxxy
mul r1.zw, r1.zzzw, cb0[4].xxxy
dp2 r0.w, r1.zwzz, r1.zwzz
add r0.xy, -r0.xyxx, r2.xyxx
mul r0.xy, r0.xyxx, cb0[4].xyxx
dp2 r0.x, r0.xyxx, r0.xyxx
sqrt r3.xy, r0.wxww
add r0.xy, -r2.xyxx, r1.xyxx
mul r0.xy, r0.xyxx, cb0[4].xyxx
dp2 r0.x, r0.xyxx, r0.xyxx
sqrt r3.z, r0.x
min r0.x, r3.y, r3.x
min r3.w, r3.z, r0.x
min r1.xyzw, r3.xyzw, l(9.000000, 9.000000, 9.000000, 9.000000)
and r0.xyzw, r0.zzzz, r1.xyzw
store_structured u0.xyzw, vThreadID.x, l(0), r0.xyzw
endif
ret
// Approximately 180 instruction slots used
|
.include "m328Pdef.inc"
.org 0x000
_blinks:
ldi r23, 0xa
add r24, r23
clr r1
clr r25
ret
|
; A092270: If n mod 2 == 0 then 3^n else 2^n.
; 1,2,9,8,81,32,729,128,6561,512,59049,2048,531441,8192,4782969,32768,43046721,131072,387420489,524288,3486784401,2097152,31381059609,8388608,282429536481,33554432,2541865828329,134217728,22876792454961,536870912,205891132094649
mov $1,$0
gcd $0,2
add $0,1
pow $0,$1
|
COMMENT @%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Copyright (c) GeoWorks 1992 -- All Rights Reserved
PROJECT: GEOS
MODULE: Bitmap Library
FILE: drawRectTool.asm
AUTHOR: Steve Yegge, Oct 6, 1992
REVISION HISTORY:
Name Date Description
---- ---- -----------
SY 10/ 6/92 Initial revision
DESCRIPTION:
This file implements a non-filled rectangle tool.
$Id: drawRectTool.asm,v 1.1 97/04/04 17:43:20 newdeal Exp $
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%@
BitmapClassStructures segment resource
DrawRectToolClass
BitmapClassStructures ends
BitmapToolCodeResource segment resource ;start of tool code resource
DrawRectToolDraw method DrawRectToolClass, MSG_TOOL_DRAW
uses cx, dx
.enter
mov ax, ds:[di].TI_initialX
mov bx, ds:[di].TI_initialY
mov cx, ds:[di].TI_previousX
mov dx, ds:[di].TI_previousY
call DragToolAdjustCoordsBeforeGrRoutine
EditBitmap DrawRectToolFillRect
.leave
ret
DrawRectToolDraw endm
DrawRectToolFillRect proc far
;
; make sure the lower-right corner is moved up, because
; we're only interested in pixel-oriented rectangles.
; (so we want the frame to be drawn TO the lower right
; pixel, not PAST it, as is the norm in the graphics
; system).
;
cmp ax, cx
jl decCX
dec ax
jmp short bottom
decCX:
dec cx
bottom:
cmp bx, dx
jl decDX
dec bx
jmp short doIt
decDX:
dec dx
doIt:
call GrDrawRect
ret
DrawRectToolFillRect endp
BitmapToolCodeResource ends ;end of tool code resource
|
; A056120: a(n) = (3^3)*4^(n-3) with a(0)=1, a(1)=1 and a(2)=7.
; 1,1,7,27,108,432,1728,6912,27648,110592,442368,1769472,7077888,28311552,113246208,452984832,1811939328,7247757312,28991029248,115964116992,463856467968,1855425871872
mov $1,3
lpb $0,1
sub $0,1
mul $1,2
lpe
mov $2,$1
mul $1,2
mul $1,$2
div $1,16
sub $1,1
div $1,2
mul $1,3
div $1,4
add $1,1
|
; A054567: a(n) = 4*n^2 - 7*n + 4.
; 1,6,19,40,69,106,151,204,265,334,411,496,589,690,799,916,1041,1174,1315,1464,1621,1786,1959,2140,2329,2526,2731,2944,3165,3394,3631,3876,4129,4390,4659,4936,5221,5514,5815,6124,6441,6766,7099,7440,7789,8146,8511,8884,9265,9654,10051,10456,10869,11290,11719,12156,12601,13054,13515,13984,14461,14946,15439,15940,16449,16966,17491,18024,18565,19114,19671,20236,20809,21390,21979,22576,23181,23794,24415,25044,25681,26326,26979,27640,28309,28986,29671,30364,31065,31774,32491,33216,33949,34690,35439,36196,36961,37734,38515,39304,40101,40906,41719,42540,43369,44206,45051,45904,46765,47634,48511,49396,50289,51190,52099,53016,53941,54874,55815,56764,57721,58686,59659,60640,61629,62626,63631,64644,65665,66694,67731,68776,69829,70890,71959,73036,74121,75214,76315,77424,78541,79666,80799,81940,83089,84246,85411,86584,87765,88954,90151,91356,92569,93790,95019,96256,97501,98754,100015,101284,102561,103846,105139,106440,107749,109066,110391,111724,113065,114414,115771,117136,118509,119890,121279,122676,124081,125494,126915,128344,129781,131226,132679,134140,135609,137086,138571,140064,141565,143074,144591,146116,147649,149190,150739,152296,153861,155434,157015,158604,160201,161806,163419,165040,166669,168306,169951,171604,173265,174934,176611,178296,179989,181690,183399,185116,186841,188574,190315,192064,193821,195586,197359,199140,200929,202726,204531,206344,208165,209994,211831,213676,215529,217390,219259,221136,223021,224914,226815,228724,230641,232566,234499,236440,238389,240346,242311,244284,246265,248254
mov $1,$0
add $1,$0
pow $1,2
add $1,$0
add $1,1
|
; A074155: Group the natural numbers so that the product of members of a group is a multiple of the sum: (1),(2,3,4,5,6),(7,8,9),(10,11,12),(13,14,15),(16,17,18),(19,20,21),(22,23,24),.... This is the sequence of the ratio of product /sum.
; 1,36,21,40,65,96,133,176,225,280,341,408,481,560,645,736,833,936,1045,1160,1281,1408,1541,1680,1825,1976,2133,2296,2465,2640,2821,3008,3201,3400,3605,3816,4033,4256,4485,4720,4961,5208,5461,5720,5985,6256,6533
mov $1,$0
mul $1,3
mov $2,$0
pow $0,9
trn $1,$0
mul $1,14
add $1,1
mov $3,$2
mul $3,4
add $1,$3
mov $4,$2
mul $4,$2
mov $3,$4
mul $3,3
add $1,$3
|
// Bindings for the python frontend
#include <optional>
#include <string>
#include "taichi/ir/snode.h"
#if TI_WITH_LLVM
#include "llvm/Config/llvm-config.h"
#endif
#include "pybind11/functional.h"
#include "pybind11/pybind11.h"
#include "pybind11/eigen.h"
#include "pybind11/numpy.h"
#include "taichi/ir/expression_ops.h"
#include "taichi/ir/frontend_ir.h"
#include "taichi/ir/statements.h"
#include "taichi/program/graph_builder.h"
#include "taichi/program/extension.h"
#include "taichi/program/async_engine.h"
#include "taichi/program/ndarray.h"
#include "taichi/python/export.h"
#include "taichi/math/svd.h"
#include "taichi/util/statistics.h"
#include "taichi/util/action_recorder.h"
#include "taichi/system/timeline.h"
#include "taichi/python/snode_registry.h"
#include "taichi/program/sparse_matrix.h"
#include "taichi/program/sparse_solver.h"
#include "taichi/aot/graph_data.h"
#include "taichi/ir/mesh.h"
#include "taichi/program/kernel_profiler.h"
#if defined(TI_WITH_CUDA)
#include "taichi/backends/cuda/cuda_context.h"
#endif
TI_NAMESPACE_BEGIN
bool test_threading();
TI_NAMESPACE_END
TLANG_NAMESPACE_BEGIN
void async_print_sfg();
std::string async_dump_dot(std::optional<std::string> rankdir,
int embed_states_threshold);
Expr expr_index(const Expr &expr, const Expr &index) {
return expr[index];
}
std::string libdevice_path();
TLANG_NAMESPACE_END
TI_NAMESPACE_BEGIN
void export_lang(py::module &m) {
using namespace taichi::lang;
py::register_exception<TaichiTypeError>(m, "TaichiTypeError",
PyExc_TypeError);
py::register_exception<TaichiSyntaxError>(m, "TaichiSyntaxError",
PyExc_SyntaxError);
py::register_exception<TaichiRuntimeError>(m, "TaichiRuntimeError",
PyExc_RuntimeError);
py::register_exception<TaichiAssertionError>(m, "TaichiAssertionError",
PyExc_AssertionError);
py::enum_<Arch>(m, "Arch", py::arithmetic())
#define PER_ARCH(x) .value(#x, Arch::x)
#include "taichi/inc/archs.inc.h"
#undef PER_ARCH
.export_values();
m.def("arch_name", arch_name);
m.def("arch_from_name", arch_from_name);
py::enum_<SNodeType>(m, "SNodeType", py::arithmetic())
#define PER_SNODE(x) .value(#x, SNodeType::x)
#include "taichi/inc/snodes.inc.h"
#undef PER_SNODE
.export_values();
py::enum_<Extension>(m, "Extension", py::arithmetic())
#define PER_EXTENSION(x) .value(#x, Extension::x)
#include "taichi/inc/extensions.inc.h"
#undef PER_EXTENSION
.export_values();
py::enum_<ExternalArrayLayout>(m, "Layout", py::arithmetic())
.value("AOS", ExternalArrayLayout::kAOS)
.value("SOA", ExternalArrayLayout::kSOA)
.value("NULL", ExternalArrayLayout::kNull)
.export_values();
py::enum_<AutodiffMode>(m, "AutodiffMode", py::arithmetic())
.value("NONE", AutodiffMode::kNone)
.value("FORWARD", AutodiffMode::kForward)
.value("REVERSE", AutodiffMode::kReverse)
.export_values();
// TODO(type): This should be removed
py::class_<DataType>(m, "DataType")
.def(py::init<Type *>())
.def(py::self == py::self)
.def("__hash__", &DataType::hash)
.def("to_string", &DataType::to_string)
.def("__str__", &DataType::to_string)
.def(
"get_ptr", [](DataType *dtype) -> Type * { return *dtype; },
py::return_value_policy::reference)
.def(py::pickle(
[](const DataType &dt) {
// Note: this only works for primitive types, which is fine for now.
auto primitive =
dynamic_cast<const PrimitiveType *>((const Type *)dt);
TI_ASSERT(primitive);
return py::make_tuple((std::size_t)primitive->type);
},
[](py::tuple t) {
if (t.size() != 1)
throw std::runtime_error("Invalid state!");
DataType dt =
PrimitiveType::get((PrimitiveTypeID)(t[0].cast<std::size_t>()));
return dt;
}));
py::class_<CompileConfig>(m, "CompileConfig")
.def(py::init<>())
.def_readwrite("arch", &CompileConfig::arch)
.def_readwrite("opt_level", &CompileConfig::opt_level)
.def_readwrite("packed", &CompileConfig::packed)
.def_readwrite("print_ir", &CompileConfig::print_ir)
.def_readwrite("print_preprocessed_ir",
&CompileConfig::print_preprocessed_ir)
.def_readwrite("debug", &CompileConfig::debug)
.def_readwrite("cfg_optimization", &CompileConfig::cfg_optimization)
.def_readwrite("check_out_of_bound", &CompileConfig::check_out_of_bound)
.def_readwrite("print_accessor_ir", &CompileConfig::print_accessor_ir)
.def_readwrite("print_evaluator_ir", &CompileConfig::print_evaluator_ir)
.def_readwrite("use_llvm", &CompileConfig::use_llvm)
.def_readwrite("print_benchmark_stat",
&CompileConfig::print_benchmark_stat)
.def_readwrite("print_struct_llvm_ir",
&CompileConfig::print_struct_llvm_ir)
.def_readwrite("print_kernel_llvm_ir",
&CompileConfig::print_kernel_llvm_ir)
.def_readwrite("print_kernel_llvm_ir_optimized",
&CompileConfig::print_kernel_llvm_ir_optimized)
.def_readwrite("print_kernel_nvptx", &CompileConfig::print_kernel_nvptx)
.def_readwrite("simplify_before_lower_access",
&CompileConfig::simplify_before_lower_access)
.def_readwrite("simplify_after_lower_access",
&CompileConfig::simplify_after_lower_access)
.def_readwrite("lower_access", &CompileConfig::lower_access)
.def_readwrite("move_loop_invariant_outside_if",
&CompileConfig::move_loop_invariant_outside_if)
.def_readwrite("default_cpu_block_dim",
&CompileConfig::default_cpu_block_dim)
.def_readwrite("default_gpu_block_dim",
&CompileConfig::default_gpu_block_dim)
.def_readwrite("gpu_max_reg", &CompileConfig::gpu_max_reg)
.def_readwrite("saturating_grid_dim", &CompileConfig::saturating_grid_dim)
.def_readwrite("max_block_dim", &CompileConfig::max_block_dim)
.def_readwrite("cpu_max_num_threads", &CompileConfig::cpu_max_num_threads)
.def_readwrite("random_seed", &CompileConfig::random_seed)
.def_readwrite("verbose_kernel_launches",
&CompileConfig::verbose_kernel_launches)
.def_readwrite("verbose", &CompileConfig::verbose)
.def_readwrite("demote_dense_struct_fors",
&CompileConfig::demote_dense_struct_fors)
.def_readwrite("kernel_profiler", &CompileConfig::kernel_profiler)
.def_readwrite("timeline", &CompileConfig::timeline)
.def_readwrite("default_fp", &CompileConfig::default_fp)
.def_readwrite("default_ip", &CompileConfig::default_ip)
.def_readwrite("device_memory_GB", &CompileConfig::device_memory_GB)
.def_readwrite("device_memory_fraction",
&CompileConfig::device_memory_fraction)
.def_readwrite("fast_math", &CompileConfig::fast_math)
.def_readwrite("advanced_optimization",
&CompileConfig::advanced_optimization)
.def_readwrite("ad_stack_size", &CompileConfig::ad_stack_size)
.def_readwrite("async_mode", &CompileConfig::async_mode)
.def_readwrite("dynamic_index", &CompileConfig::dynamic_index)
.def_readwrite("flatten_if", &CompileConfig::flatten_if)
.def_readwrite("make_thread_local", &CompileConfig::make_thread_local)
.def_readwrite("make_block_local", &CompileConfig::make_block_local)
.def_readwrite("detect_read_only", &CompileConfig::detect_read_only)
.def_readwrite("ndarray_use_cached_allocator",
&CompileConfig::ndarray_use_cached_allocator)
.def_readwrite("use_mesh", &CompileConfig::use_mesh)
.def_readwrite("cc_compile_cmd", &CompileConfig::cc_compile_cmd)
.def_readwrite("cc_link_cmd", &CompileConfig::cc_link_cmd)
.def_readwrite("async_opt_passes", &CompileConfig::async_opt_passes)
.def_readwrite("async_opt_fusion", &CompileConfig::async_opt_fusion)
.def_readwrite("async_opt_fusion_max_iter",
&CompileConfig::async_opt_fusion_max_iter)
.def_readwrite("async_opt_listgen", &CompileConfig::async_opt_listgen)
.def_readwrite("async_opt_activation_demotion",
&CompileConfig::async_opt_activation_demotion)
.def_readwrite("async_opt_dse", &CompileConfig::async_opt_dse)
.def_readwrite("async_listgen_fast_filtering",
&CompileConfig::async_listgen_fast_filtering)
.def_readwrite("async_opt_intermediate_file",
&CompileConfig::async_opt_intermediate_file)
.def_readwrite("async_flush_every", &CompileConfig::async_flush_every)
.def_readwrite("async_max_fuse_per_task",
&CompileConfig::async_max_fuse_per_task)
.def_readwrite("quant_opt_store_fusion",
&CompileConfig::quant_opt_store_fusion)
.def_readwrite("quant_opt_atomic_demotion",
&CompileConfig::quant_opt_atomic_demotion)
.def_readwrite("allow_nv_shader_extension",
&CompileConfig::allow_nv_shader_extension)
.def_readwrite("use_gles", &CompileConfig::use_gles)
.def_readwrite("make_mesh_block_local",
&CompileConfig::make_mesh_block_local)
.def_readwrite("mesh_localize_to_end_mapping",
&CompileConfig::mesh_localize_to_end_mapping)
.def_readwrite("mesh_localize_from_end_mapping",
&CompileConfig::mesh_localize_from_end_mapping)
.def_readwrite("optimize_mesh_reordered_mapping",
&CompileConfig::optimize_mesh_reordered_mapping)
.def_readwrite("mesh_localize_all_attr_mappings",
&CompileConfig::mesh_localize_all_attr_mappings)
.def_readwrite("demote_no_access_mesh_fors",
&CompileConfig::demote_no_access_mesh_fors)
.def_readwrite("experimental_auto_mesh_local",
&CompileConfig::experimental_auto_mesh_local)
.def_readwrite("auto_mesh_local_default_occupacy",
&CompileConfig::auto_mesh_local_default_occupacy)
.def_readwrite("offline_cache", &CompileConfig::offline_cache)
.def_readwrite("offline_cache_file_path",
&CompileConfig::offline_cache_file_path);
m.def("reset_default_compile_config",
[&]() { default_compile_config = CompileConfig(); });
m.def(
"default_compile_config",
[&]() -> CompileConfig & { return default_compile_config; },
py::return_value_policy::reference);
py::class_<Program::KernelProfilerQueryResult>(m, "KernelProfilerQueryResult")
.def_readwrite("counter", &Program::KernelProfilerQueryResult::counter)
.def_readwrite("min", &Program::KernelProfilerQueryResult::min)
.def_readwrite("max", &Program::KernelProfilerQueryResult::max)
.def_readwrite("avg", &Program::KernelProfilerQueryResult::avg);
py::class_<KernelProfileTracedRecord>(m, "KernelProfileTracedRecord")
.def_readwrite("register_per_thread",
&KernelProfileTracedRecord::register_per_thread)
.def_readwrite("shared_mem_per_block",
&KernelProfileTracedRecord::shared_mem_per_block)
.def_readwrite("grid_size", &KernelProfileTracedRecord::grid_size)
.def_readwrite("block_size", &KernelProfileTracedRecord::block_size)
.def_readwrite(
"active_blocks_per_multiprocessor",
&KernelProfileTracedRecord::active_blocks_per_multiprocessor)
.def_readwrite("kernel_time",
&KernelProfileTracedRecord::kernel_elapsed_time_in_ms)
.def_readwrite("base_time", &KernelProfileTracedRecord::time_since_base)
.def_readwrite("name", &KernelProfileTracedRecord::name)
.def_readwrite("metric_values",
&KernelProfileTracedRecord::metric_values);
py::enum_<SNodeAccessFlag>(m, "SNodeAccessFlag", py::arithmetic())
.value("block_local", SNodeAccessFlag::block_local)
.value("read_only", SNodeAccessFlag::read_only)
.value("mesh_local", SNodeAccessFlag::mesh_local)
.export_values();
// Export ASTBuilder
py::class_<ASTBuilder>(m, "ASTBuilder")
.def("make_id_expr", &ASTBuilder::make_id_expr)
.def("create_kernel_exprgroup_return",
&ASTBuilder::create_kernel_exprgroup_return)
.def("create_print", &ASTBuilder::create_print)
.def("begin_func", &ASTBuilder::begin_func)
.def("end_func", &ASTBuilder::end_func)
.def("stop_grad", &ASTBuilder::stop_gradient)
.def("begin_frontend_if", &ASTBuilder::begin_frontend_if)
.def("begin_frontend_if_true", &ASTBuilder::begin_frontend_if_true)
.def("pop_scope", &ASTBuilder::pop_scope)
.def("begin_frontend_if_false", &ASTBuilder::begin_frontend_if_false)
.def("insert_deactivate", &ASTBuilder::insert_snode_deactivate)
.def("insert_activate", &ASTBuilder::insert_snode_activate)
.def("insert_external_func_call", &ASTBuilder::insert_external_func_call)
.def("expr_alloca", &ASTBuilder::expr_alloca)
.def("expr_alloca_local_tensor", &ASTBuilder::expr_alloca_local_tensor)
.def("create_assert_stmt", &ASTBuilder::create_assert_stmt)
.def("expr_assign", &ASTBuilder::expr_assign)
.def("begin_frontend_range_for", &ASTBuilder::begin_frontend_range_for)
.def("end_frontend_range_for", &ASTBuilder::pop_scope)
.def("begin_frontend_struct_for", &ASTBuilder::begin_frontend_struct_for)
.def("end_frontend_struct_for", &ASTBuilder::pop_scope)
.def("begin_frontend_mesh_for", &ASTBuilder::begin_frontend_mesh_for)
.def("end_frontend_mesh_for", &ASTBuilder::pop_scope)
.def("begin_frontend_while", &ASTBuilder::begin_frontend_while)
.def("insert_break_stmt", &ASTBuilder::insert_break_stmt)
.def("insert_continue_stmt", &ASTBuilder::insert_continue_stmt)
.def("insert_expr_stmt", &ASTBuilder::insert_expr_stmt)
.def("insert_thread_idx_expr", &ASTBuilder::insert_thread_idx_expr)
.def("insert_patch_idx_expr", &ASTBuilder::insert_patch_idx_expr)
.def("sifakis_svd_f32", sifakis_svd_export<float32, int32>)
.def("sifakis_svd_f64", sifakis_svd_export<float64, int64>)
.def("expr_var", &ASTBuilder::make_var)
.def("bit_vectorize", &ASTBuilder::bit_vectorize)
.def("parallelize", &ASTBuilder::parallelize)
.def("strictly_serialize", &ASTBuilder::strictly_serialize)
.def("block_dim", &ASTBuilder::block_dim)
.def("insert_snode_access_flag", &ASTBuilder::insert_snode_access_flag)
.def("reset_snode_access_flag", &ASTBuilder::reset_snode_access_flag);
py::class_<Program>(m, "Program")
.def(py::init<>())
.def_readonly("config", &Program::config)
.def("sync_kernel_profiler",
[](Program *program) { program->profiler->sync(); })
.def("query_kernel_profile_info",
[](Program *program, const std::string &name) {
return program->query_kernel_profile_info(name);
})
.def("get_kernel_profiler_records",
[](Program *program) {
return program->profiler->get_traced_records();
})
.def(
"get_kernel_profiler_device_name",
[](Program *program) { return program->profiler->get_device_name(); })
.def("reinit_kernel_profiler_with_metrics",
[](Program *program, const std::vector<std::string> metrics) {
return program->profiler->reinit_with_metrics(metrics);
})
.def("kernel_profiler_total_time",
[](Program *program) { return program->profiler->get_total_time(); })
.def("set_kernel_profiler_toolkit",
[](Program *program, const std::string toolkit_name) {
return program->profiler->set_profiler_toolkit(toolkit_name);
})
.def("clear_kernel_profile_info", &Program::clear_kernel_profile_info)
.def("timeline_clear",
[](Program *) { Timelines::get_instance().clear(); })
.def("timeline_save",
[](Program *, const std::string &fn) {
Timelines::get_instance().save(fn);
})
.def("print_memory_profiler_info", &Program::print_memory_profiler_info)
.def("finalize", &Program::finalize)
.def("get_total_compilation_time", &Program::get_total_compilation_time)
.def("visualize_layout", &Program::visualize_layout)
.def("get_snode_num_dynamically_allocated",
&Program::get_snode_num_dynamically_allocated)
.def("benchmark_rebuild_graph",
[](Program *program) {
program->async_engine->sfg->benchmark_rebuild_graph();
})
.def("synchronize", &Program::synchronize)
.def("async_flush", &Program::async_flush)
.def("materialize_runtime", &Program::materialize_runtime)
.def("make_aot_module_builder", &Program::make_aot_module_builder)
.def("get_snode_tree_size", &Program::get_snode_tree_size)
.def("get_snode_root", &Program::get_snode_root,
py::return_value_policy::reference)
.def("current_ast_builder", &Program::current_ast_builder,
py::return_value_policy::reference)
.def(
"create_kernel",
[](Program *program, const std::function<void(Kernel *)> &body,
const std::string &name, AutodiffMode autodiff_mode) -> Kernel * {
py::gil_scoped_release release;
return &program->kernel(body, name, autodiff_mode);
},
py::return_value_policy::reference)
.def("create_function", &Program::create_function,
py::return_value_policy::reference)
.def("create_sparse_matrix_builder",
[](Program *program, int n, int m, uint64 max_num_entries,
DataType dtype, const std::string &storage_format) {
TI_ERROR_IF(!arch_is_cpu(program->config.arch),
"SparseMatrix only supports CPU for now.");
return SparseMatrixBuilder(n, m, max_num_entries, dtype,
storage_format);
})
.def("create_sparse_matrix",
[](Program *program, int n, int m, DataType dtype,
std::string storage_format) {
TI_ERROR_IF(!arch_is_cpu(program->config.arch),
"SparseMatrix only supports CPU for now.");
return make_sparse_matrix(n, m, dtype, storage_format);
})
.def("make_sparse_matrix_from_ndarray",
[](Program *program, SparseMatrix &sm, const Ndarray &ndarray) {
TI_ERROR_IF(!arch_is_cpu(program->config.arch),
"SparseMatrix only supports CPU for now.");
return make_sparse_matrix_from_ndarray(program, sm, ndarray);
})
.def(
"dump_dot",
[](Program *program, std::optional<std::string> rankdir,
int embed_states_threshold) {
// https://pybind11.readthedocs.io/en/stable/advanced/functions.html#allow-prohibiting-none-arguments
return program->async_engine->sfg->dump_dot(rankdir,
embed_states_threshold);
},
py::arg("rankdir").none(true),
py::arg("embed_states_threshold")) // FIXME:
.def("no_activate",
[](Program *program, SNode *snode) {
// TODO(#2193): Also apply to @ti.func?
auto *kernel = dynamic_cast<Kernel *>(program->current_callable);
TI_ASSERT(kernel);
kernel->no_activate.push_back(snode);
})
.def("print_sfg",
[](Program *program) { return program->async_engine->sfg->print(); })
.def("decl_arg",
[&](Program *program, const DataType &dt, bool is_array) {
return program->current_callable->insert_arg(dt, is_array);
})
.def("decl_arr_arg",
[&](Program *program, const DataType &dt, int total_dim,
std::vector<int> shape) {
return program->current_callable->insert_arr_arg(dt, total_dim,
shape);
})
.def("decl_ret",
[&](Program *program, const DataType &dt) {
return program->current_callable->insert_ret(dt);
})
.def("make_id_expr",
[](Program *program, const std::string &name) {
return Expr::make<IdExpression>(program->get_next_global_id(name));
})
.def(
"create_ndarray",
[&](Program *program, const DataType &dt,
const std::vector<int> &shape,
const std::vector<int> &element_shape,
ExternalArrayLayout layout) -> Ndarray * {
return program->create_ndarray(dt, shape, element_shape, layout);
},
py::arg("dt"), py::arg("shape"),
py::arg("element_shape") = py::tuple(),
py::arg("layout") = ExternalArrayLayout::kNull,
py::return_value_policy::reference)
.def("get_ndarray_data_ptr_as_int",
[](Program *program, Ndarray *ndarray) {
return program->get_ndarray_data_ptr_as_int(ndarray);
})
.def("fill_float",
[](Program *program, Ndarray *ndarray, float val) {
program->fill_ndarray_fast(ndarray,
reinterpret_cast<uint32_t &>(val));
})
.def("fill_int",
[](Program *program, Ndarray *ndarray, int32_t val) {
program->fill_ndarray_fast(ndarray,
reinterpret_cast<int32_t &>(val));
})
.def("fill_uint",
[](Program *program, Ndarray *ndarray, uint32_t val) {
program->fill_ndarray_fast(ndarray, val);
})
.def("global_var_expr_from_snode", [](Program *program, SNode *snode) {
return Expr::make<GlobalVariableExpression>(
snode, program->get_next_global_id());
});
py::class_<AotModuleBuilder>(m, "AotModuleBuilder")
.def("add_field", &AotModuleBuilder::add_field)
.def("add", &AotModuleBuilder::add)
.def("add_kernel_template", &AotModuleBuilder::add_kernel_template)
.def("add_graph", &AotModuleBuilder::add_graph)
.def("dump", &AotModuleBuilder::dump);
py::class_<Axis>(m, "Axis").def(py::init<int>());
py::class_<SNode>(m, "SNode")
.def(py::init<>())
.def_readwrite("parent", &SNode::parent)
.def_readonly("type", &SNode::type)
.def_readonly("id", &SNode::id)
.def("dense",
(SNode & (SNode::*)(const std::vector<Axis> &,
const std::vector<int> &, bool))(&SNode::dense),
py::return_value_policy::reference)
.def(
"pointer",
(SNode & (SNode::*)(const std::vector<Axis> &,
const std::vector<int> &, bool))(&SNode::pointer),
py::return_value_policy::reference)
.def("hash",
(SNode & (SNode::*)(const std::vector<Axis> &,
const std::vector<int> &, bool))(&SNode::hash),
py::return_value_policy::reference)
.def("dynamic", &SNode::dynamic, py::return_value_policy::reference)
.def("bitmasked",
(SNode & (SNode::*)(const std::vector<Axis> &,
const std::vector<int> &,
bool))(&SNode::bitmasked),
py::return_value_policy::reference)
.def("bit_struct", &SNode::bit_struct, py::return_value_policy::reference)
.def("bit_array", &SNode::bit_array, py::return_value_policy::reference)
.def("place", &SNode::place)
.def("data_type", [](SNode *snode) { return snode->dt; })
.def("name", [](SNode *snode) { return snode->name; })
.def("get_num_ch",
[](SNode *snode) -> int { return (int)snode->ch.size(); })
.def(
"get_ch",
[](SNode *snode, int i) -> SNode * { return snode->ch[i].get(); },
py::return_value_policy::reference)
.def("lazy_grad", &SNode::lazy_grad)
.def("read_int", &SNode::read_int)
.def("read_uint", &SNode::read_uint)
.def("read_float", &SNode::read_float)
.def("has_adjoint", &SNode::has_adjoint)
.def("has_dual", &SNode::has_dual)
.def("is_primal", &SNode::is_primal)
.def("is_place", &SNode::is_place)
.def("get_expr", &SNode::get_expr)
.def("write_int", &SNode::write_int)
.def("write_float", &SNode::write_float)
.def("get_shape_along_axis", &SNode::shape_along_axis)
.def("get_physical_index_position",
[](SNode *snode) {
return std::vector<int>(
snode->physical_index_position,
snode->physical_index_position + taichi_max_num_indices);
})
.def("num_active_indices",
[](SNode *snode) { return snode->num_active_indices; })
.def_readonly("cell_size_bytes", &SNode::cell_size_bytes)
.def_readonly("offset_bytes_in_parent_cell",
&SNode::offset_bytes_in_parent_cell)
.def("begin_shared_exp_placement", &SNode::begin_shared_exp_placement)
.def("end_shared_exp_placement", &SNode::end_shared_exp_placement);
py::class_<SNodeTree>(m, "SNodeTree")
.def("id", &SNodeTree::id)
.def("destroy_snode_tree", [](SNodeTree *snode_tree, Program *program) {
program->destroy_snode_tree(snode_tree);
});
py::class_<Ndarray>(m, "Ndarray")
.def("device_allocation_ptr", &Ndarray::get_device_allocation_ptr_as_int)
.def("element_size", &Ndarray::get_element_size)
.def("nelement", &Ndarray::get_nelement)
.def("read_int", &Ndarray::read_int)
.def("read_uint", &Ndarray::read_uint)
.def("read_float", &Ndarray::read_float)
.def("write_int", &Ndarray::write_int)
.def("write_float", &Ndarray::write_float)
.def("total_shape", &Ndarray::total_shape)
.def_readonly("dtype", &Ndarray::dtype)
.def_readonly("element_shape", &Ndarray::element_shape)
.def_readonly("shape", &Ndarray::shape);
py::enum_<aot::ArgKind>(m, "ArgKind")
.value("SCALAR", aot::ArgKind::kScalar)
.value("NDARRAY", aot::ArgKind::kNdarray)
.export_values();
py::class_<aot::Arg>(m, "Arg")
.def(py::init<aot::ArgKind, std::string, DataType &, std::vector<int>>(),
py::arg("tag"), py::arg("name"), py::arg("dtype"),
py::arg("element_shape") = py::tuple())
.def_readonly("name", &aot::Arg::name)
.def_readonly("element_shape", &aot::Arg::element_shape)
.def("dtype", &aot::Arg::dtype);
py::class_<Node>(m, "Node");
py::class_<Sequential, Node>(m, "Sequential")
.def(py::init<GraphBuilder *>())
.def("append", &Sequential::append)
.def("dispatch", &Sequential::dispatch);
py::class_<GraphBuilder>(m, "GraphBuilder")
.def(py::init<>())
.def("dispatch", &GraphBuilder::dispatch)
.def("compile", &GraphBuilder::compile)
.def("create_sequential", &GraphBuilder::new_sequential_node,
py::return_value_policy::reference)
.def("seq", &GraphBuilder::seq, py::return_value_policy::reference);
py::class_<aot::CompiledGraph>(m, "CompiledGraph")
.def("run", [](aot::CompiledGraph *self, const py::dict &arg_ptrs,
const py::dict &arg_ints, const py::dict &arg_floats) {
std::unordered_map<std::string, aot::IValue> args;
for (auto it : arg_ptrs) {
auto &val = it.second.cast<Ndarray &>();
args.insert(
{py::cast<std::string>(it.first), aot::IValue::create(val)});
}
for (auto it : arg_ints) {
args.insert({py::cast<std::string>(it.first),
aot::IValue::create(py::cast<int>(it.second))});
}
for (auto it : arg_floats) {
args.insert({py::cast<std::string>(it.first),
aot::IValue::create(py::cast<double>(it.second))});
}
self->run(args);
});
py::class_<Kernel>(m, "Kernel")
.def("get_ret_int", &Kernel::get_ret_int)
.def("get_ret_float", &Kernel::get_ret_float)
.def("get_ret_int_tensor", &Kernel::get_ret_int_tensor)
.def("get_ret_float_tensor", &Kernel::get_ret_float_tensor)
.def("make_launch_context", &Kernel::make_launch_context)
.def(
"ast_builder",
[](Kernel *self) -> ASTBuilder * {
return &self->context->builder();
},
py::return_value_policy::reference)
.def("__call__",
[](Kernel *kernel, Kernel::LaunchContextBuilder &launch_ctx) {
py::gil_scoped_release release;
kernel->operator()(launch_ctx);
});
py::class_<Kernel::LaunchContextBuilder>(m, "KernelLaunchContext")
.def("set_arg_int", &Kernel::LaunchContextBuilder::set_arg_int)
.def("set_arg_float", &Kernel::LaunchContextBuilder::set_arg_float)
.def("set_arg_external_array",
&Kernel::LaunchContextBuilder::set_arg_external_array)
.def("set_arg_external_array_with_shape",
&Kernel::LaunchContextBuilder::set_arg_external_array_with_shape)
.def("set_arg_ndarray", &Kernel::LaunchContextBuilder::set_arg_ndarray)
.def("set_extra_arg_int",
&Kernel::LaunchContextBuilder::set_extra_arg_int);
py::class_<Function>(m, "Function")
.def("set_function_body",
py::overload_cast<const std::function<void()> &>(
&Function::set_function_body))
.def(
"ast_builder",
[](Function *self) -> ASTBuilder * {
return &self->context->builder();
},
py::return_value_policy::reference);
py::class_<Expr> expr(m, "Expr");
expr.def("snode", &Expr::snode, py::return_value_policy::reference)
.def("is_global_var",
[](Expr *expr) { return expr->is<GlobalVariableExpression>(); })
.def("is_external_var",
[](Expr *expr) { return expr->is<ExternalTensorExpression>(); })
.def("is_global_ptr",
[](Expr *expr) { return expr->is<GlobalPtrExpression>(); })
.def("is_primal",
[](Expr *expr) {
return expr->cast<GlobalVariableExpression>()->is_primal;
})
.def("set_tb", &Expr::set_tb)
.def("set_name",
[&](Expr *expr, std::string na) {
expr->cast<GlobalVariableExpression>()->name = na;
})
.def("set_is_primal",
[&](Expr *expr, bool v) {
expr->cast<GlobalVariableExpression>()->is_primal = v;
})
.def("set_adjoint", &Expr::set_adjoint)
.def("set_dual", &Expr::set_dual)
.def("set_attribute", &Expr::set_attribute)
.def("get_ret_type", &Expr::get_ret_type)
.def("type_check", &Expr::type_check)
.def("get_expr_name",
[](Expr *expr) {
return expr->cast<GlobalVariableExpression>()->name;
})
.def("get_attribute", &Expr::get_attribute)
.def("get_raw_address", [](Expr *expr) { return (uint64)expr; })
.def("get_underlying_ptr_address", [](Expr *e) {
// The reason that there are both get_raw_address() and
// get_underlying_ptr_address() is that Expr itself is mostly wrapper
// around its underlying |expr| (of type Expression). Expr |e| can be
// temporary, while the underlying |expr| is mostly persistant.
//
// Same get_raw_address() implies that get_underlying_ptr_address() are
// also the same. The reverse is not true.
return (uint64)e->expr.get();
});
py::class_<ExprGroup>(m, "ExprGroup")
.def(py::init<>())
.def("size", [](ExprGroup *eg) { return eg->exprs.size(); })
.def("push_back", &ExprGroup::push_back);
py::class_<Stmt>(m, "Stmt");
m.def("expr_get_addr", [](SNode *snode, const ExprGroup &indices) {
return Expr::make<SNodeOpExpression>(snode, SNodeOpType::get_addr, indices);
});
m.def("insert_append",
[](SNode *snode, const ExprGroup &indices, const Expr &val) {
return snode_append(snode, indices, val);
});
m.def("insert_is_active", [](SNode *snode, const ExprGroup &indices) {
return snode_is_active(snode, indices);
});
m.def("insert_len", [](SNode *snode, const ExprGroup &indices) {
return snode_length(snode, indices);
});
m.def("insert_internal_func_call",
[&](const std::string &func_name, const ExprGroup &args,
bool with_runtime_context) {
return Expr::make<InternalFuncCallExpression>(func_name, args.exprs,
with_runtime_context);
});
m.def("make_func_call_expr",
Expr::make<FuncCallExpression, Function *, const ExprGroup &>);
m.def("value_cast", static_cast<Expr (*)(const Expr &expr, DataType)>(cast));
m.def("bits_cast",
static_cast<Expr (*)(const Expr &expr, DataType)>(bit_cast));
m.def("expr_atomic_add", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::add, a, b);
});
m.def("expr_atomic_sub", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::sub, a, b);
});
m.def("expr_atomic_min", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::min, a, b);
});
m.def("expr_atomic_max", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::max, a, b);
});
m.def("expr_atomic_bit_and", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::bit_and, a, b);
});
m.def("expr_atomic_bit_or", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::bit_or, a, b);
});
m.def("expr_atomic_bit_xor", [&](const Expr &a, const Expr &b) {
return Expr::make<AtomicOpExpression>(AtomicOpType::bit_xor, a, b);
});
m.def("expr_index", expr_index);
m.def("expr_assume_in_range", assume_range);
m.def("expr_loop_unique", loop_unique);
#define DEFINE_EXPRESSION_OP(x) m.def("expr_" #x, expr_##x);
DEFINE_EXPRESSION_OP(neg)
DEFINE_EXPRESSION_OP(sqrt)
DEFINE_EXPRESSION_OP(round)
DEFINE_EXPRESSION_OP(floor)
DEFINE_EXPRESSION_OP(ceil)
DEFINE_EXPRESSION_OP(abs)
DEFINE_EXPRESSION_OP(sin)
DEFINE_EXPRESSION_OP(asin)
DEFINE_EXPRESSION_OP(cos)
DEFINE_EXPRESSION_OP(acos)
DEFINE_EXPRESSION_OP(tan)
DEFINE_EXPRESSION_OP(tanh)
DEFINE_EXPRESSION_OP(inv)
DEFINE_EXPRESSION_OP(rcp)
DEFINE_EXPRESSION_OP(rsqrt)
DEFINE_EXPRESSION_OP(exp)
DEFINE_EXPRESSION_OP(log)
DEFINE_EXPRESSION_OP(select)
DEFINE_EXPRESSION_OP(ifte)
DEFINE_EXPRESSION_OP(cmp_le)
DEFINE_EXPRESSION_OP(cmp_lt)
DEFINE_EXPRESSION_OP(cmp_ge)
DEFINE_EXPRESSION_OP(cmp_gt)
DEFINE_EXPRESSION_OP(cmp_ne)
DEFINE_EXPRESSION_OP(cmp_eq)
DEFINE_EXPRESSION_OP(bit_and)
DEFINE_EXPRESSION_OP(bit_or)
DEFINE_EXPRESSION_OP(bit_xor)
DEFINE_EXPRESSION_OP(bit_shl)
DEFINE_EXPRESSION_OP(bit_shr)
DEFINE_EXPRESSION_OP(bit_sar)
DEFINE_EXPRESSION_OP(bit_not)
DEFINE_EXPRESSION_OP(logic_not)
DEFINE_EXPRESSION_OP(logical_and)
DEFINE_EXPRESSION_OP(logical_or)
DEFINE_EXPRESSION_OP(add)
DEFINE_EXPRESSION_OP(sub)
DEFINE_EXPRESSION_OP(mul)
DEFINE_EXPRESSION_OP(div)
DEFINE_EXPRESSION_OP(truediv)
DEFINE_EXPRESSION_OP(floordiv)
DEFINE_EXPRESSION_OP(mod)
DEFINE_EXPRESSION_OP(max)
DEFINE_EXPRESSION_OP(min)
DEFINE_EXPRESSION_OP(atan2)
DEFINE_EXPRESSION_OP(pow)
#undef DEFINE_EXPRESSION_OP
m.def("make_global_load_stmt", Stmt::make<GlobalLoadStmt, Stmt *>);
m.def("make_global_store_stmt", Stmt::make<GlobalStoreStmt, Stmt *, Stmt *>);
m.def("make_frontend_assign_stmt",
Stmt::make<FrontendAssignStmt, const Expr &, const Expr &>);
m.def("make_arg_load_expr",
Expr::make<ArgLoadExpression, int, const DataType &, bool>);
m.def("make_reference", Expr::make<ReferenceExpression, const Expr &>);
m.def("make_external_tensor_expr",
Expr::make<ExternalTensorExpression, const DataType &, int, int, int,
const std::vector<int> &>);
m.def("make_rand_expr", Expr::make<RandExpression, const DataType &>);
m.def("make_const_expr_int",
Expr::make<ConstExpression, const DataType &, int64>);
m.def("make_const_expr_fp",
Expr::make<ConstExpression, const DataType &, float64>);
m.def("make_global_ptr_expr",
Expr::make<GlobalPtrExpression, const Expr &, const ExprGroup &>);
auto &&bin = py::enum_<BinaryOpType>(m, "BinaryOpType", py::arithmetic());
for (int t = 0; t <= (int)BinaryOpType::undefined; t++)
bin.value(binary_op_type_name(BinaryOpType(t)).c_str(), BinaryOpType(t));
bin.export_values();
m.def("make_binary_op_expr",
Expr::make<BinaryOpExpression, const BinaryOpType &, const Expr &,
const Expr &>);
auto &&unary = py::enum_<UnaryOpType>(m, "UnaryOpType", py::arithmetic());
for (int t = 0; t <= (int)UnaryOpType::undefined; t++)
unary.value(unary_op_type_name(UnaryOpType(t)).c_str(), UnaryOpType(t));
unary.export_values();
m.def("make_unary_op_expr",
Expr::make<UnaryOpExpression, const UnaryOpType &, const Expr &>);
#define PER_TYPE(x) \
m.attr(("DataType_" + data_type_name(PrimitiveType::x)).c_str()) = \
PrimitiveType::x;
#include "taichi/inc/data_type.inc.h"
#undef PER_TYPE
m.def("data_type_size", data_type_size);
m.def("is_custom_type", is_custom_type);
m.def("is_integral", is_integral);
m.def("is_signed", is_signed);
m.def("is_real", is_real);
m.def("is_unsigned", is_unsigned);
m.def("global_new", static_cast<Expr (*)(Expr, DataType)>(global_new));
m.def("set_global_grad", [&](const Expr &expr) {
TI_ASSERT(expr.is<GlobalVariableExpression>());
expr.cast<GlobalVariableExpression>()->is_primal = false;
});
m.def("data_type_name", data_type_name);
m.def("subscript", [](const Expr &expr, const ExprGroup &expr_group) {
return expr[expr_group];
});
m.def("make_tensor_element_expr",
Expr::make<TensorElementExpression, const Expr &, const ExprGroup &,
const std::vector<int> &, int>);
m.def("get_external_tensor_dim", [](const Expr &expr) {
TI_ASSERT(expr.is<ExternalTensorExpression>());
return expr.cast<ExternalTensorExpression>()->dim;
});
m.def("get_external_tensor_shape_along_axis",
Expr::make<ExternalTensorShapeAlongAxisExpression, const Expr &, int>);
// Mesh related.
m.def("get_relation_size", [](mesh::MeshPtr mesh_ptr, const Expr &mesh_idx,
mesh::MeshElementType to_type) {
return Expr::make<MeshRelationAccessExpression>(mesh_ptr.ptr.get(),
mesh_idx, to_type);
});
m.def("get_relation_access",
[](mesh::MeshPtr mesh_ptr, const Expr &mesh_idx,
mesh::MeshElementType to_type, const Expr &neighbor_idx) {
return Expr::make<MeshRelationAccessExpression>(
mesh_ptr.ptr.get(), mesh_idx, to_type, neighbor_idx);
});
m.def("get_index_conversion",
[](mesh::MeshPtr mesh_ptr, mesh::MeshElementType idx_type,
const Expr &idx, mesh::ConvType &conv_type) {
return Expr::make<MeshIndexConversionExpression>(
mesh_ptr.ptr.get(), idx_type, idx, conv_type);
});
py::class_<FunctionKey>(m, "FunctionKey")
.def(py::init<const std::string &, int, int>())
.def_readonly("instance_id", &FunctionKey::instance_id);
m.def("test_throw", [] {
try {
throw IRModified();
} catch (IRModified) {
TI_INFO("caught");
}
});
m.def("test_throw", [] { throw IRModified(); });
m.def("needs_grad", needs_grad);
#if TI_WITH_LLVM
m.def("libdevice_path", libdevice_path);
#endif
m.def("host_arch", host_arch);
m.def("set_lib_dir", [&](const std::string &dir) { compiled_lib_dir = dir; });
m.def("set_tmp_dir", [&](const std::string &dir) { runtime_tmp_dir = dir; });
m.def("get_commit_hash", get_commit_hash);
m.def("get_version_string", get_version_string);
m.def("get_version_major", get_version_major);
m.def("get_version_minor", get_version_minor);
m.def("get_version_patch", get_version_patch);
m.def("get_llvm_target_support", [] {
#if defined(TI_WITH_LLVM)
return LLVM_VERSION_STRING;
#else
return "targets unsupported";
#endif
});
m.def("test_printf", [] { printf("test_printf\n"); });
m.def("test_logging", [] { TI_INFO("test_logging"); });
m.def("trigger_crash", [] { *(int *)(1) = 0; });
m.def("get_max_num_indices", [] { return taichi_max_num_indices; });
m.def("get_max_num_args", [] { return taichi_max_num_args; });
m.def("test_threading", test_threading);
m.def("is_extension_supported", is_extension_supported);
m.def("print_stat", [] { stat.print(); });
m.def("stat", [] {
std::string result;
stat.print(&result);
return result;
});
m.def("record_action_entry",
[](std::string name,
std::vector<std::pair<std::string,
std::variant<std::string, int, float>>> args) {
std::vector<ActionArg> acts;
for (auto const &[k, v] : args) {
if (std::holds_alternative<int>(v)) {
acts.push_back(ActionArg(k, std::get<int>(v)));
} else if (std::holds_alternative<float>(v)) {
acts.push_back(ActionArg(k, std::get<float>(v)));
} else {
acts.push_back(ActionArg(k, std::get<std::string>(v)));
}
}
ActionRecorder::get_instance().record(name, acts);
});
m.def("start_recording", [](const std::string &fn) {
ActionRecorder::get_instance().start_recording(fn);
});
m.def("stop_recording",
[]() { ActionRecorder::get_instance().stop_recording(); });
m.def("query_int64", [](const std::string &key) {
if (key == "cuda_compute_capability") {
#if defined(TI_WITH_CUDA)
return CUDAContext::get_instance().get_compute_capability();
#else
TI_NOT_IMPLEMENTED
#endif
} else {
TI_ERROR("Key {} not supported in query_int64", key);
}
});
// Type system
py::class_<Type>(m, "Type").def("to_string", &Type::to_string);
// Note that it is important to specify py::return_value_policy::reference for
// the factory methods, otherwise pybind11 will delete the Types owned by
// TypeFactory on Python-scope pointer destruction.
py::class_<TypeFactory>(m, "TypeFactory")
.def("get_custom_int_type", &TypeFactory::get_custom_int_type,
py::arg("num_bits"), py::arg("is_signed"), py::arg("compute_type"),
py::return_value_policy::reference)
.def("get_custom_float_type", &TypeFactory::get_custom_float_type,
py::arg("digits_type"), py::arg("exponent_type"),
py::arg("compute_type"), py::arg("scale"),
py::return_value_policy::reference);
m.def("get_type_factory_instance", TypeFactory::get_instance,
py::return_value_policy::reference);
m.def("decl_tensor_type",
[&](std::vector<int> shape, const DataType &element_type) {
return TypeFactory::create_tensor_type(shape, element_type);
});
py::class_<SNodeRegistry>(m, "SNodeRegistry")
.def(py::init<>())
.def("create_root", &SNodeRegistry::create_root,
py::return_value_policy::reference);
m.def(
"finalize_snode_tree",
[](SNodeRegistry *registry, const SNode *root, Program *program,
bool compile_only) -> SNodeTree * {
return program->add_snode_tree(registry->finalize(root), compile_only);
},
py::return_value_policy::reference);
// Sparse Matrix
py::class_<SparseMatrixBuilder>(m, "SparseMatrixBuilder")
.def("print_triplets", &SparseMatrixBuilder::print_triplets)
.def("build", &SparseMatrixBuilder::build)
.def("get_addr", [](SparseMatrixBuilder *mat) { return uint64(mat); });
py::class_<SparseMatrix>(m, "SparseMatrix")
.def(py::init<>())
.def(py::init<int, int, DataType>(), py::arg("rows"), py::arg("cols"),
py::arg("dt") = PrimitiveType::f32)
.def(py::init<SparseMatrix &>())
.def("to_string", &SparseMatrix::to_string)
.def("get_element", &SparseMatrix::get_element<float32>)
.def("set_element", &SparseMatrix::set_element<float32>)
.def("num_rows", &SparseMatrix::num_rows)
.def("num_cols", &SparseMatrix::num_cols);
#define MAKE_SPARSE_MATRIX(TYPE, STORAGE, VTYPE) \
using STORAGE##TYPE##EigenMatrix = \
Eigen::SparseMatrix<float##TYPE, Eigen::STORAGE>; \
py::class_<EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>, SparseMatrix>( \
m, #VTYPE #STORAGE "_EigenSparseMatrix") \
.def(py::init<int, int, DataType>()) \
.def(py::init<EigenSparseMatrix<STORAGE##TYPE##EigenMatrix> &>()) \
.def(py::init<const STORAGE##TYPE##EigenMatrix &>()) \
.def(py::self += py::self) \
.def(py::self + py::self) \
.def(py::self -= py::self) \
.def(py::self - py::self) \
.def(py::self *= float##TYPE()) \
.def(py::self *float##TYPE()) \
.def(float##TYPE() * py::self) \
.def(py::self *py::self) \
.def("matmul", &EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>::matmul) \
.def("transpose", \
&EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>::transpose) \
.def("get_element", \
&EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>::get_element< \
float##TYPE>) \
.def("set_element", \
&EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>::set_element< \
float##TYPE>) \
.def("mat_vec_mul", \
&EigenSparseMatrix<STORAGE##TYPE##EigenMatrix>::mat_vec_mul< \
Eigen::VectorX##VTYPE>);
MAKE_SPARSE_MATRIX(32, ColMajor, f);
MAKE_SPARSE_MATRIX(32, RowMajor, f);
MAKE_SPARSE_MATRIX(64, ColMajor, d);
MAKE_SPARSE_MATRIX(64, RowMajor, d);
py::class_<SparseSolver>(m, "SparseSolver")
.def("compute", &SparseSolver::compute)
.def("analyze_pattern", &SparseSolver::analyze_pattern)
.def("factorize", &SparseSolver::factorize)
.def("solve", &SparseSolver::solve)
.def("info", &SparseSolver::info);
m.def("make_sparse_solver", &make_sparse_solver);
// Mesh Class
// Mesh related.
py::enum_<mesh::MeshTopology>(m, "MeshTopology", py::arithmetic())
.value("Triangle", mesh::MeshTopology::Triangle)
.value("Tetrahedron", mesh::MeshTopology::Tetrahedron)
.export_values();
py::enum_<mesh::MeshElementType>(m, "MeshElementType", py::arithmetic())
.value("Vertex", mesh::MeshElementType::Vertex)
.value("Edge", mesh::MeshElementType::Edge)
.value("Face", mesh::MeshElementType::Face)
.value("Cell", mesh::MeshElementType::Cell)
.export_values();
py::enum_<mesh::MeshRelationType>(m, "MeshRelationType", py::arithmetic())
.value("VV", mesh::MeshRelationType::VV)
.value("VE", mesh::MeshRelationType::VE)
.value("VF", mesh::MeshRelationType::VF)
.value("VC", mesh::MeshRelationType::VC)
.value("EV", mesh::MeshRelationType::EV)
.value("EE", mesh::MeshRelationType::EE)
.value("EF", mesh::MeshRelationType::EF)
.value("EC", mesh::MeshRelationType::EC)
.value("FV", mesh::MeshRelationType::FV)
.value("FE", mesh::MeshRelationType::FE)
.value("FF", mesh::MeshRelationType::FF)
.value("FC", mesh::MeshRelationType::FC)
.value("CV", mesh::MeshRelationType::CV)
.value("CE", mesh::MeshRelationType::CE)
.value("CF", mesh::MeshRelationType::CF)
.value("CC", mesh::MeshRelationType::CC)
.export_values();
py::enum_<mesh::ConvType>(m, "ConvType", py::arithmetic())
.value("l2g", mesh::ConvType::l2g)
.value("l2r", mesh::ConvType::l2r)
.value("g2r", mesh::ConvType::g2r)
.export_values();
py::class_<mesh::Mesh>(m, "Mesh");
py::class_<mesh::MeshPtr>(m, "MeshPtr");
m.def("element_order", mesh::element_order);
m.def("from_end_element_order", mesh::from_end_element_order);
m.def("to_end_element_order", mesh::to_end_element_order);
m.def("relation_by_orders", mesh::relation_by_orders);
m.def("inverse_relation", mesh::inverse_relation);
m.def("element_type_name", mesh::element_type_name);
m.def(
"create_mesh",
[]() {
auto mesh_shared = std::make_shared<mesh::Mesh>();
mesh::MeshPtr mesh_ptr = mesh::MeshPtr{mesh_shared};
return mesh_ptr;
},
py::return_value_policy::reference);
// ad-hoc setters
m.def("set_owned_offset",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshElementType type, SNode *snode) {
mesh_ptr.ptr->owned_offset.insert(std::pair(type, snode));
});
m.def("set_total_offset",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshElementType type, SNode *snode) {
mesh_ptr.ptr->total_offset.insert(std::pair(type, snode));
});
m.def("set_num_patches", [](mesh::MeshPtr &mesh_ptr, int num_patches) {
mesh_ptr.ptr->num_patches = num_patches;
});
m.def("set_num_elements", [](mesh::MeshPtr &mesh_ptr,
mesh::MeshElementType type, int num_elements) {
mesh_ptr.ptr->num_elements.insert(std::pair(type, num_elements));
});
m.def("get_num_elements",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshElementType type) {
return mesh_ptr.ptr->num_elements.find(type)->second;
});
m.def("set_patch_max_element_num",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshElementType type,
int max_element_num) {
mesh_ptr.ptr->patch_max_element_num.insert(
std::pair(type, max_element_num));
});
m.def("set_index_mapping",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshElementType element_type,
mesh::ConvType conv_type, SNode *snode) {
mesh_ptr.ptr->index_mapping.insert(
std::make_pair(std::make_pair(element_type, conv_type), snode));
});
m.def("set_relation_fixed",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshRelationType type, SNode *value) {
mesh_ptr.ptr->relations.insert(
std::pair(type, mesh::MeshLocalRelation(value)));
});
m.def("set_relation_dynamic",
[](mesh::MeshPtr &mesh_ptr, mesh::MeshRelationType type, SNode *value,
SNode *patch_offset, SNode *offset) {
mesh_ptr.ptr->relations.insert(std::pair(
type, mesh::MeshLocalRelation(value, patch_offset, offset)));
});
}
TI_NAMESPACE_END
|
;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;
; Car_Icon.asm R.J.Evans 4/11/17 Section 001
;
; Icon colors per pixel for an 8x8 car icon
;
;
.ORIG x4000
Car_Icon .FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x7C00
.FILL x7C00
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x7C00
.FILL x0000
.FILL x0000
.FILL x7C00
.FILL x7C00
.FILL x0000
.FILL x0000
.FILL x0000
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x0000
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7C00
.FILL x7FED
.FILL x0000
.FILL x001F
.FILL x001F
.FILL x0000
.FILL x0000
.FILL x001F
.FILL x001F
.FILL x0000
.FILL x0000
.FILL x001F
.FILL x001F
.FILL x0000
.FILL x0000
.FILL x001F
.FILL x001F
.FILL x0000
.END |
#include "SignalProcessing.h"
/*
* SignalProcessing.cpp
*
* Created on: Dec 6, 2018
* Author: JD
*/
constexpr COMPUTATION_TYPE hanning_window(int n, int total) {
return std::sin(PI * n / (total - 1)) * sin(PI * n / (total - 1));
}
constexpr COMPUTATION_TYPE real_filter(int n, int total) {
return std::cos(TWO_PI * n * BIN_INDEX / total) * hanning_window(n, total);
}
constexpr COMPUTATION_TYPE imag_filter(int n, int total) {
return -(std::sin(TWO_PI * n * BIN_INDEX / total) * hanning_window(n, total));
}
void compute_block(computation &c, int index, uint16_t * block, size_t length) {
for (auto i = 0; i < length; ++i) {
c.real += static_cast<COMPUTATION_TYPE>(lut.values[i + index * DMA_Block][0] * static_cast<COMPUTATION_TYPE>(block[i]));
c.imag += static_cast<COMPUTATION_TYPE>(lut.values[i + index * DMA_Block][1] * static_cast<COMPUTATION_TYPE>(block[i]));
}
}
// Not sure if this does anything, but what I'm hoping to do here is store the lut to flash
// Which is being done currently...
#pragma DATA_SECTION(".lut")
#pragma RETAIN
const Table<SAMPLE_LENGTH> lut = Table<SAMPLE_LENGTH>();
|
; A107858: a(n) = b(k), where b(k) = Fibonacci(n-1) and k = floor( n*(1+sqrt(5))/2 ).
; 1,1,2,3,7,11,28,45,117,189,494,799,2091,3383,8856,14329,37513,60697,158906,257115,673135,1089155,2851444,4613733,12078909,19544085,51167078,82790071,216747219,350704367,918155952,1485607537,3889371025
mul $0,6
div $0,4
seq $0,187107 ; Number of nontrivial compositions of differential operations and directional derivative of the n-th order on the space R^9.
div $0,2
sub $0,3
|
PewterCityObject:
db $a ; border block
db $7 ; warps
db $7, $e, $0, MUSEUM_1F
db $5, $14, $2, MUSEUM_1F
db $11, $10, $0, PEWTER_GYM
db $d, $1d, $0, PEWTER_HOUSE_1
db $11, $17, $0, PEWTER_MART
db $1d, $7, $0, PEWTER_HOUSE_2
db $19, $d, $0, PEWTER_POKECENTER
db $7 ; signs
db $1d, $13, $6 ; PewterCityText6
db $13, $21, $7 ; PewterCityText7
db $11, $18, $8 ; MartSignText
db $19, $e, $9 ; PokeCenterSignText
db $9, $f, $a ; PewterCityText10
db $11, $b, $b ; PewterCityText11
db $17, $19, $c ; PewterCityText12
db $5 ; objects
object SPRITE_LASS, $8, $f, STAY, NONE, $1 ; person
object SPRITE_BLACK_HAIR_BOY_1, $11, $19, STAY, NONE, $2 ; person
object SPRITE_BLACK_HAIR_BOY_2, $1b, $11, STAY, NONE, $3 ; person
object SPRITE_BLACK_HAIR_BOY_2, $1a, $19, WALK, $2, $4 ; person
object SPRITE_BUG_CATCHER, $23, $10, STAY, DOWN, $5 ; person
; warp-to
EVENT_DISP PEWTER_CITY_WIDTH, $7, $e ; MUSEUM_1F
EVENT_DISP PEWTER_CITY_WIDTH, $5, $14 ; MUSEUM_1F
EVENT_DISP PEWTER_CITY_WIDTH, $11, $10 ; PEWTER_GYM
EVENT_DISP PEWTER_CITY_WIDTH, $d, $1d ; PEWTER_HOUSE_1
EVENT_DISP PEWTER_CITY_WIDTH, $11, $17 ; PEWTER_MART
EVENT_DISP PEWTER_CITY_WIDTH, $1d, $7 ; PEWTER_HOUSE_2
EVENT_DISP PEWTER_CITY_WIDTH, $19, $d ; PEWTER_POKECENTER
|
.intel_syntax noprefix
.global _Z4mainv
.global _Z10Start_Testv
.section .text #.text
_Z10Start_Testv:
mov ecx, 6 #Return_Value100, 6
jmp Return_Here_132 #Return_Here_132
Return_Here_132:
mov r8d, ecx #REG_Return_Value1000, Return_Value100
mov r9, rdx #REG_Return_Value1000_REMAINDER28253, REMAINDER_6868
mov eax, 3 #3_QUOTIENT7711, 3
mul r8d #REG_Return_Value1000
mov r8d, eax #REG_Return_Value1000, 3_QUOTIENT7711
mov rdx, r9 #REMAINDER_6868, REG_Return_Value1000_REMAINDER28253
mov r8d, r8d #c, REG_Return_Value1000
mov r9d, r8d #REG_c1, c
xor edx, edx #REG_c1_REMAINDER27644, REG_c1_REMAINDER27644
mov eax, r9d #REG_c1_QUOTIENT25547, REG_c1
div ecx #Return_Value100
mov r9d, eax #REG_c1, REG_c1_QUOTIENT25547
mov ecx, r9d #d, REG_c1
add ecx, 3 #d, 3
add ecx, 6 #d, 6
sub ecx, r8d #d, c
mov eax, ecx #Returning_REG2, d
ret #
mov ecx, 1065353216 #REG_1065385878, 1065353216
movd xmm0, ecx #MEDIA_1065385973, REG_1065385878
movss xmm0, xmm0 #Return_Value101, MEDIA_1065385973
jmp Return_Here_133 #Return_Here_133
Return_Here_133:
cvttss2si ecx, xmm0 #REG_Return_Value1013, Return_Value101
mov eax, ecx #Returning_REG4, REG_Return_Value1013
ret #
mov eax, -6 #Returning_REG5, -6
ret #
ret #
_Z4mainv:
mov ecx, 6 #Return_Value100_102, 6
jmp Return_Here_135 #Return_Here_135
Return_Here_135:
mov r8d, ecx #REG_Return_Value100_1020, Return_Value100_102
mov r9, rdx #REG_Return_Value100_1020_REMAINDER12859, REMAINDER_8723
mov eax, 3 #3_QUOTIENT20037, 3
mul r8d #REG_Return_Value100_1020
mov r8d, eax #REG_Return_Value100_1020, 3_QUOTIENT20037
mov rdx, r9 #REMAINDER_8723, REG_Return_Value100_1020_REMAINDER12859
mov r8d, r8d #c_102, REG_Return_Value100_1020
mov r8d, r8d #REG_c_1021, c_102
xor edx, edx #REG_c_1021_REMAINDER27529, REG_c_1021_REMAINDER27529
mov eax, r8d #REG_c_1021_QUOTIENT9741, REG_c_1021
div ecx #Return_Value100_102
mov r8d, eax #REG_c_1021, REG_c_1021_QUOTIENT9741
mov ecx, r8d #d_102, REG_c_1021
jmp Return_Here_134 #Return_Here_134
mov ecx, 1065353216 #REG_1065353994, 1065353216
movd xmm0, ecx #MEDIA_1065365532, REG_1065353994
movss xmm0, xmm0 #Return_Value101_102, MEDIA_1065365532
jmp Return_Here_136 #Return_Here_136
Return_Here_136:
jmp Return_Here_134 #Return_Here_134
jmp Return_Here_134 #Return_Here_134
Return_Here_134:
mov eax, 1 #Returning_REG2, 1
ret #
ret #
.section .data #.data
std_MAX_CONSOLE_BUFFER_LENGHT:
.long 4096 #4096
std_GENERIC_WRITE:
.long 1073741824 #1073741824
std_GENERIC_READ:
.quad 2147483648 #2147483648
std_FILE_SHARE_NONE:
.long 0 #0
std_FILE_SHARE_READ:
.long 1 #1
std_FILE_SHARE_WRITE:
.long 2 #2
std_FILE_SHARE_DELETE:
.long 4 #4
std_CREATE_NEW:
.long 1 #1
std_CREATE_ALWAYS:
.long 2 #2
std_OPEN_EXISTING:
.long 3 #3
std_OPEN_ALWAYS:
.long 4 #4
std_TRUNCATE_EXISTING:
.long 4 #4
std_FILE_ATTRIBUTE_NORMAL:
.long 128 #128
std_FILE_ATTRIBUTE_FOLDER:
.long 16 #16
std_MAXIMUM_PATH_LENGTH:
.long 260 #260
std_ERROR_INSUFFICIENT_BUFFER:
.long 122 #122
std_MINIMUM_PROCESS_FILENAME_LENGTH:
.long 50 #50
|
// Copyright (c) 2019-2020 The Ocvcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <bench/bench.h>
#include <crypto/chacha20.h>
/* Number of bytes to process per iteration */
static const uint64_t BUFFER_SIZE_TINY = 64;
static const uint64_t BUFFER_SIZE_SMALL = 256;
static const uint64_t BUFFER_SIZE_LARGE = 1024*1024;
static void CHACHA20(benchmark::Bench& bench, size_t buffersize)
{
std::vector<uint8_t> key(32,0);
ChaCha20 ctx(key.data(), key.size());
ctx.SetIV(0);
ctx.Seek(0);
std::vector<uint8_t> in(buffersize,0);
std::vector<uint8_t> out(buffersize,0);
bench.batch(in.size()).unit("byte").run([&] {
ctx.Crypt(in.data(), out.data(), in.size());
});
}
static void CHACHA20_64BYTES(benchmark::Bench& bench)
{
CHACHA20(bench, BUFFER_SIZE_TINY);
}
static void CHACHA20_256BYTES(benchmark::Bench& bench)
{
CHACHA20(bench, BUFFER_SIZE_SMALL);
}
static void CHACHA20_1MB(benchmark::Bench& bench)
{
CHACHA20(bench, BUFFER_SIZE_LARGE);
}
BENCHMARK(CHACHA20_64BYTES);
BENCHMARK(CHACHA20_256BYTES);
BENCHMARK(CHACHA20_1MB);
|
INCLUDE "./src/include/hardware.inc"
INCLUDE "./src/include/util.inc"
INCLUDE "./src/include/hUGE.inc"
INCLUDE "./src/definitions/definitions.inc"
DEF GAME_TIMER_INCREMENT EQU $04
SECTION "Game Level WRAM", WRAM0
wGameLevelTileMap::
ds 1024 ; Every game level is made of 1024 tiles.
.end::
wGameTimer::
ds 2 ; Store the timer as Binary-Coded-Decimals (BCD) in Big-Endian
wGameTimerFrac::
ds 1
w2StarsTime::
ds 2
w3StarsTime::
ds 2
wMapSizeY::
ds 2
wMapSizeX::
ds 2
wShadowSCData::
ds 2 ; y pos, then x pos
wEndTimer::
ds 2 ; after x number of frames go to win screen/lose screen, little endian, first is fraction, second int
wGameEnd::
ds 1
SECTION "Game Level", ROM0
; Global Jumps
JumpLoadGameLevel::
jp LoadGameLevel
; Local Jumps
JumpVBlankHandler:
jp VBlankHandler
JumpUpdateGameLevel:
jp UpdateGameLevel
JumpUpdatePausedGameLevel:
jp UpdatePausedGameLevel
LCDOn:
ld a, LCDCF_ON | LCDCF_WIN9C00 | LCDCF_WINON | LCDCF_BG9800 | LCDCF_OBJ16 | LCDCF_OBJON | LCDCF_BGON
ld [hLCDC], a ; Store a copy of the flags in HRAM.
ld [rLCDC], a
ret
InitStageParam:
; Set Game Timer Frac
xor a
ld [wGameTimerFrac], a
ld [wEndTimer], a
ld [wEndTimer + 1], a
ld [wGameEnd], a
call GetSelectedStageParamAddr
inc hl
inc hl
; Set Game Timer
ld a, [hli]
ld [wGameTimer], a
ld a, [hli]
ld [wGameTimer+1], a
; Set 2-Stars time.
ld a, [hli]
ld [w2StarsTime], a
ld a, [hli]
ld [w2StarsTime+1], a
; Set 3-Stars time.
ld a, [hli]
ld [w3StarsTime], a
ld a, [hli]
ld [w3StarsTime+1], a
ret
InitStage:
ld a, [wSelectedStage]
FOR N, 1, MAX_STAGES
dec a
jp z, InitStage{u:N}
ENDR
; Default
jp InitStage0
LoadGameLevel:
di ; Disable Interrupts
call LCDOff
call SoundOff
ld hl, JumpVBlankHandler
call SetVBlankCallback
ld hl, JumpUpdateGameLevel
call SetProgramLoopCallback
; Copy background tile data into VRAM.
set_romx_bank BANK(BGWindowTileData)
mem_copy BGWindowTileData, _VRAM9000, BGWindowTileData.end-BGWindowTileData
; Copy font tile data into VRAM.
set_romx_bank BANK(FontTileDataEN)
mem_copy FontTileDataEN, _VRAM9200, FontTileDataEN.end-FontTileDataEN
; Load Sprites into VRAM.
set_romx_bank BANK(Sprites)
mem_copy Sprites, _VRAM8000, Sprites.end-Sprites
; Reset OAM & Shadow OAM.
call ResetOAM
mem_set_small wShadowOAM, 0, wShadowOAM.end - wShadowOAM
xor a
ld [wCurrentShadowOAMPtr], a
; Transfer sprite data to OAM.
call hOAMDMA
call ResetPlayerCamera
call ResetAllBullets
; Reset rSCY & rSCX
xor a
ld [rSCY], a
ld [rSCX], a
; Initalise Stage Specific Stuff
call InitStageParam
call InitStage
; Initialise UI (Needs to be called after InitStageParam.)
call ResetBGWindowUpdateQueue
call LoadGameLevelUI
call UpdateGameTimerUI
call UpdatePlayerHPUI
call UpdateEnemyCounterUI
call LCDOn
; Set BGM
call SoundOn
set_romx_bank BANK(GameLevelBGM)
ld hl, GameLevelBGM
call hUGE_init
ld b, $00
ld c, $01
call hUGE_mute_channel
; Set STAT interrupt flags.
ld a, VIEWPORT_SIZE_Y
ldh [rLYC], a
ld a, STATF_LYC
ldh [rSTAT], a
; Set Interrupt Flags
ld a, IEF_VBLANK | IEF_STAT
ldh [rIE], a
; Clear Pending Interrupts
xor a
ldh [rIF], a
ei ; Enable Master Interrupt Switch
ret
UpdateGameLevel:
call UpdateInput
set_romx_bank BANK(Sprites)
call ResetShadowOAM
; insert game logic here and update shadow OAM data
call UpdateParticleEffect
call UpdateGameLevelTimer ; update timer
ld a, [wPlayer_HP]
and a, a
jr z, .updateRest
.updatePlayer
call UpdatePlayerMovement
call UpdatePlayerAttack
call UpdatePlayerCamera
call UpdatePlayerShadowOAM
.updateRest
call UpdateAllEnemies
call UpdateBullets
call UpdatePowerUpShadowOAM
; Dirty tiles get updated during HBlank.
call UpdateBGWindow
; Update Sound
set_romx_bank BANK(GameLevelBGM)
call _hUGE_dosound
; Check for pause.
ld a, [wNewlyInputKeys]
ld b, a
bit PADB_START, b
call nz, PauseGame
ret
UpdatePausedGameLevel:
; Check for resume
call UpdateInput
ld a, [wNewlyInputKeys]
ld b, a
.resume
bit PADB_START, b
jr z, .reset
call ResumeGame
jr .end
.reset
bit PADB_SELECT, b
jr z, .quit
ld hl, JumpLoadGameLevel
call SetProgramLoopCallback
.quit
bit PADB_B, b
jr z, .end
ld hl, JumpLoadMainMenu
call SetProgramLoopCallback
.end
ret
VBlankHandler:
push af
; If VBlankHandler was called without waiting for VBlank, the frame lagged.
ld a, [hWaitVBlankFlag]
and a
jr z, .lagFrame
; Reset hWaitVBlankFlag
xor a
ld [hWaitVBlankFlag], a
push bc
push de
push hl
; Enable Sprite Rendering
ldh a, [hLCDC]
ldh [rLCDC], a
call hOAMDMA ; Update OAM
; Update Camera Position
ld a, [wShadowSCData]
ld [rSCY], a
ld a, [wShadowSCData + 1]
ld [rSCX], a
pop hl
pop de
pop bc
pop af
.lagFrame
pop af
reti
; Get the value of the tile, given a tile index.
; @param bc TileIndex
; @return a Tile Value
GetGameLevelTileValue::
push hl
ld hl, wGameLevelTileMap
add hl, bc
ld a, [hl]
pop hl
ret
; Set a tile to be updated.
; @param a New Tile Value
; @param bc Tile Index
SetGameLevelTile::
push af
push hl
ld hl, wGameLevelTileMap
add hl, bc
ld [hl], a
pop hl
pop af
call QueueBGTile
ret
UpdateGameLevelTimer:
ld a, [wGameEnd]
and a, a
jr nz, UpdateEndGameTimer
; Update timer
ld a, [wGameTimerFrac]
add a, GAME_TIMER_INCREMENT
ld [wGameTimerFrac], a
ret nc
; Load game timer value into hl.
ld a, [wGameTimer]
ld h, a
ld a, [wGameTimer+1]
ld l, a
; hl - 1
sub a, $01
daa
ld l, a
ld a, h
sbc a, $00
daa
ld h, a
; Save new game timer value.
ld a, h
ld [wGameTimer], a
ld a, l
ld [wGameTimer+1], a
call UpdateGameTimerUI
; If h == l == 0, HP == 0. If HP == 0, lose.
ld a, h
or a, l
jr nz, .end
ld a, LOSE_REASON_TIME
ld [wLoseReason], a
ld hl, JumpLoadLoseScreen
call SetProgramLoopCallback
.end
ret
/* Update the end game timer */
UpdateEndGameTimer::
ld a, [wEndTimer]
add a, GAME_TIMER_INCREMENT
ld [wEndTimer], a
ret nc
ld a, [wEndTimer + 1]
inc a ; add carry
ld [wEndTimer + 1], a
cp a, GAME_END_TIME
ret nz
; check how the game ended, whether enemies all died or player died
ld a, [wCurrLevelEnemiesNo]
and a, a
jr z, .playerWon
.playerLost ; player lost all health
ld a, LOSE_REASON_HP
ld [wLoseReason], a
ld hl, JumpLoadLoseScreen
call SetProgramLoopCallback
ret
.playerWon ; all enemies defeated
call SaveCurrentScore
; Unlock next stage.
ld a, [wSelectedStage]
inc a
ld [wRWIndex], a
call UnlockStage
ld hl, JumpLoadWinScreen
call SetProgramLoopCallback
ret
PauseGame::
; Set STAT interrupt flags.
ld a, PAUSE_VIEWPORT_SIZE_Y
ldh [rLYC], a
ld a, STATF_LYC
ldh [rSTAT], a
call PauseUI
ld hl, JumpUpdatePausedGameLevel
call SetProgramLoopCallback
call SoundOff
ret
ResumeGame::
; Set STAT interrupt flags.
ld a, VIEWPORT_SIZE_Y
ldh [rLYC], a
ld a, STATF_LYC
ldh [rSTAT], a
call ResumeUI
ld hl, JumpUpdateGameLevel
call SetProgramLoopCallback
call SoundOn
ret
SaveCurrentScore::
; Load Previous Save Data
ld a, [wSelectedStage]
ld [wRWIndex], a
call LoadGame
; bc = -current time.
ld a, [wGameTimer]
cpl
ld b, a
ld a, [wGameTimer+1]
cpl
ld c, a
inc bc
; Has this stage been cleared before? If no, overwrite new data. Otherwise, compare to see if old score is better.
ld a, [wRWBuffer]
cp a, STAGE_UNLOCKED_CLEARED ; Only possible states should be STAGE_UNLOCKED_NOT_CLEARED or STAGE_UNLOCKED_CLEARED. Should never be STAGE_LOCKED.
jr nz, .overwrite
; If previous time < current time (hl < bc), overwrite it. Else, do not overwrite data.
; hl = previous time.
ld a, [wRWBuffer+1]
ld h, a
ld a, [wRWBuffer+2]
ld l, a
add hl, bc
jr c, .end
.overwrite
; Set stage as cleared.
ld a, STAGE_UNLOCKED_CLEARED
ld [wRWBuffer], a
; Overwrite Time
ld a, [wGameTimer]
ld [wRWBuffer+1], a
ld a, [wGameTimer+1]
ld [wRWBuffer+2], a
; If 3 stars time <= current time, 3 stars.
ld a, [w3StarsTime]
ld h, a
ld a, [w3StarsTime+1]
ld l, a
dec hl ; add hl, bc does not set the Z flag, so we can't check for hl <= bc. Instead, we check for (hl-1)<bc
add hl, bc
jr nc, .threeStars
; If 2 stars time <= current time, 2 stars.
ld a, [w2StarsTime]
ld h, a
ld a, [w2StarsTime+1]
ld l, a
dec hl ; add hl, bc does not set the Z flag, so we can't check for hl <= bc. Instead, we check for (hl-1)<bc
add hl, bc
jr nc, .twoStars
; Else, 1 star
ld a, 1
jr .save
.threeStars
ld a, 3
jr .save
.twoStars
ld a, 2
.save
ld [wRWBuffer+3], a
call SaveGame
.end
ret |
;
; 6502 LFSR PRNG - 16-bit
; Brad Smith, 2019
; http://rainwarrior.ca
;
; A 16-bit Galois LFSR
; Possible feedback values that generate a full 65535 step sequence:
; $2D = %00101101
; $39 = %00111001
; $3F = %00111111
; $53 = %01010011
; $BD = %10111101
; $D7 = %11010111
; $39 is chosen for its compact bit pattern
; simplest version iterates the LFSR 8 times to generate 8 random bits
; 133-141 cycles per call
; 19 bytes
galois16: subroutine
ldy #8
lda Seed+0
.one
asl ; shift the register
rol Seed+1
bcc .two
eor #$39 ; apply XOR feedback whenever a 1 bit is shifted out
.two
dey
bne .one
sta Seed+0
cmp #0 ; reload flags
rts
|
; A052200: Number of n-state, 2-symbol, d+ in {LEFT, RIGHT}, 5-tuple (q, s, q+, s+, d+) (halting or not) Turing machines.
; 1,64,20736,16777216,25600000000,63403380965376,232218265089212416,1180591620717411303424,7958661109946400884391936,68719476736000000000000000000,739696442014594807059393047166976,9711967541295580042210555933809967104,152784834199652075368661148843397208866816
mul $0,2
mov $1,$0
add $1,2
sub $0,$1
mul $0,$1
sub $1,2
pow $0,$1
|
; $Id: bit_fx3.asm,v 1.4 2016/04/23 21:06:32 dom Exp $
;
; Generic platform sound effects module.
; Alternate sound library by Stefano Bodrato
;
SECTION code_clib
PUBLIC bit_fx3
PUBLIC _bit_fx3
INCLUDE "games/games.inc"
EXTERN bit_open
EXTERN bit_open_di
EXTERN bit_close
EXTERN bit_close_ei
.bit_fx3
._bit_fx3
pop bc
pop de
push de
push bc
IF sndbit_port >= 256
exx
ld bc,sndbit_port
exx
ENDIF
ld a,e
cp 8
ret nc
add a,a
ld e,a
ld d,0
ld hl,table
add hl,de
ld a,(hl)
inc hl
ld h,(hl)
ld l,a
jp (hl)
.table defw blirp2 ; effect #0
defw blirp
defw coff ; effect #2
defw blurp
defw descending
defw ascending
defw descending2
defw fx7 ; effect #7
.blirp
call bit_open_di
ld b,255
.expl
push af
ld a,sndbit_mask
ld h,0
ld l,b
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
push bc
.dly nop
djnz dly
pop bc
push af
ld a,sndbit_mask
ld h,0
ld l,b
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
push bc
push af
ld a,255
sub b
ld b,a
pop af
.dly2 nop
djnz dly2
pop bc
djnz expl
call bit_close_ei
ret
.blirp2
call bit_open_di
ld b,100
.blrp
push af
ld a,sndbit_mask
ld h,0
ld l,b
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
push bc
push af
ld a,255
sub b
ld b,a
pop af
.dlyb nop
djnz dlyb
pop bc
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
push bc
.dlya nop
djnz dlya
pop bc
djnz blrp
call bit_close_ei
ret
; Steam engine
.coff
call bit_open_di
ld hl,0
.coff2
push af
ld a,sndbit_mask
and (hl)
ld b,a
pop af
xor b
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
ld b,(hl)
.cdly
djnz cdly
inc hl
bit 7,l
jr z,coff2
call bit_close_ei
ret
.blurp
call bit_open_di
ld b,255
.blurp2
push af
ld a,sndbit_mask
ld h,0
ld l,b
and (hl)
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
push af
ld a,(hl)
.dblurp dec a
jr nz,dblurp
pop af
djnz blurp2
call bit_close_ei
ret
; descending buzzing noise
.descending
call bit_open_di
ld hl,1000
.desc1 push hl
ld b,16
.desc2 rl l
rl h
jr nc,desc3
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
.desc3
ld e,5
.desc4 dec e
jr nz,desc4
djnz desc2
pop hl
dec hl
ld c,a
ld a,h
or l
ld a,c
jr nz,desc1
call bit_close_ei
ret
; ascending buzzing noise
.ascending
call bit_open_di
ld hl,1023
.hdesc1 push hl
ld b,16
.hdesc2 rl l
rl h
jr nc,hdesc3
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
.hdesc3
djnz hdesc2
pop hl
dec hl
ld c,a
ld a,h
or l
ld a,c
jr nz,hdesc1
call bit_close_ei
ret
; descending buzzing noise #2
.descending2
call bit_open_di
ld hl,1023
.asc1 push hl
ld b,16
.asc2 rl l
rl h
jr c,asc3
xor sndbit_mask
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
.asc3
djnz asc2
pop hl
dec hl
ld c,a
ld a,h
or l
ld a,c
jr nz,asc1
call bit_close_ei
ret
; noise #7
.fx7
call bit_open_di
ld hl,4000
.fx71 push hl
push af
ld a,sndbit_mask
and l
ld l,a
pop af
xor l
IF sndbit_port >= 256
exx
out (c),a ;9 T slower
exx
ELSE
out (sndbit_port),a
ENDIF
pop hl
dec hl
ld c,a
ld a,h
or l
ld a,c
jr nz,fx71
call bit_close_ei
ret
|
; A348312: a(n) = n! * Sum_{k=0..n-1} 3^k / k!.
; Submitted by Jamie Morken(s2)
; 0,1,8,51,312,1965,13248,97839,800208,7260921,72806040,801515979,9620317512,125071036389,1751016829968,26265324194055,420245416687392,7144172815479921,128595113003161512,2443307154421058019,48866143111666389720,1026189005418216656541,22576158119430894214368
mov $2,1
mov $3,$0
lpb $3
mul $2,$3
add $1,$2
mul $1,3
sub $3,1
lpe
mov $0,$1
div $0,3
|
// Copyright (c) 2012 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 "chrome/browser/ui/views/confirm_bubble_views.h"
#include <utility>
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/confirm_bubble.h"
#include "chrome/browser/ui/confirm_bubble_model.h"
#include "chrome/browser/ui/views/chrome_layout_provider.h"
#include "chrome/browser/ui/views/chrome_typography.h"
#include "components/constrained_window/constrained_window_views.h"
#include "components/strings/grit/components_strings.h"
#include "components/vector_icons/vector_icons.h"
#include "ui/accessibility/ax_node_data.h"
#include "ui/base/buildflags.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/controls/button/image_button.h"
#include "ui/views/controls/button/image_button_factory.h"
#include "ui/views/controls/label.h"
#include "ui/views/layout/grid_layout.h"
#include "ui/views/style/typography.h"
#include "ui/views/widget/widget.h"
namespace {
std::unique_ptr<views::View> CreateExtraView(views::ButtonListener* listener) {
auto help_button = CreateVectorImageButtonWithNativeTheme(
listener, vector_icons::kHelpOutlineIcon);
help_button->SetFocusForPlatform();
help_button->SetTooltipText(l10n_util::GetStringUTF16(IDS_LEARN_MORE));
return help_button;
}
} // namespace
ConfirmBubbleViews::ConfirmBubbleViews(
std::unique_ptr<ConfirmBubbleModel> model)
: model_(std::move(model)), help_button_(nullptr) {
SetButtonLabel(ui::DIALOG_BUTTON_OK,
model_->GetButtonLabel(ui::DIALOG_BUTTON_OK));
SetButtonLabel(ui::DIALOG_BUTTON_CANCEL,
model_->GetButtonLabel(ui::DIALOG_BUTTON_CANCEL));
SetAcceptCallback(base::BindOnce(&ConfirmBubbleModel::Accept,
base::Unretained(model_.get())));
SetCancelCallback(base::BindOnce(&ConfirmBubbleModel::Cancel,
base::Unretained(model_.get())));
help_button_ = SetExtraView(::CreateExtraView(this));
set_margins(ChromeLayoutProvider::Get()->GetDialogInsetsForContentType(
views::TEXT, views::TEXT));
views::GridLayout* layout =
SetLayoutManager(std::make_unique<views::GridLayout>());
// Use a fixed maximum message width, so longer messages will wrap.
const int kMaxMessageWidth = 400;
views::ColumnSet* cs = layout->AddColumnSet(0);
cs->AddColumn(views::GridLayout::LEADING, views::GridLayout::CENTER,
views::GridLayout::kFixedSize,
views::GridLayout::ColumnSize::kFixed, kMaxMessageWidth, false);
// Add the message label.
auto label = std::make_unique<views::Label>(
model_->GetMessageText(), views::style::CONTEXT_MESSAGE_BOX_BODY_TEXT,
views::style::STYLE_SECONDARY);
DCHECK(!label->GetText().empty());
label->SetHorizontalAlignment(gfx::ALIGN_LEFT);
label->SetMultiLine(true);
label->SizeToFit(kMaxMessageWidth);
layout->StartRow(views::GridLayout::kFixedSize, 0);
label_ = layout->AddView(std::move(label));
chrome::RecordDialogCreation(chrome::DialogIdentifier::CONFIRM_BUBBLE);
}
ConfirmBubbleViews::~ConfirmBubbleViews() {
}
ui::ModalType ConfirmBubbleViews::GetModalType() const {
return ui::MODAL_TYPE_WINDOW;
}
base::string16 ConfirmBubbleViews::GetWindowTitle() const {
return model_->GetTitle();
}
bool ConfirmBubbleViews::ShouldShowCloseButton() const {
return false;
}
void ConfirmBubbleViews::ButtonPressed(views::Button* sender,
const ui::Event& event) {
if (sender == help_button_) {
model_->OpenHelpPage();
GetWidget()->Close();
}
}
void ConfirmBubbleViews::OnDialogInitialized() {
GetWidget()->GetRootView()->GetViewAccessibility().OverrideDescribedBy(
label_);
}
namespace chrome {
void ShowConfirmBubble(gfx::NativeWindow window,
gfx::NativeView anchor_view,
const gfx::Point& origin,
std::unique_ptr<ConfirmBubbleModel> model) {
constrained_window::CreateBrowserModalDialogViews(
new ConfirmBubbleViews(std::move(model)), window)
->Show();
}
} // namespace chrome
|
.global s_prepare_buffers
s_prepare_buffers:
push %r10
push %r12
push %rbp
push %rcx
push %rdi
push %rsi
lea addresses_WT_ht+0x6d57, %rsi
lea addresses_UC_ht+0xac97, %rdi
clflush (%rsi)
nop
nop
nop
nop
sub %r12, %r12
mov $124, %rcx
rep movsq
nop
nop
nop
nop
sub $60959, %r10
lea addresses_normal_ht+0x80fb, %rsi
lea addresses_D_ht+0x18197, %rdi
nop
nop
nop
add $48010, %rbp
mov $45, %rcx
rep movsb
inc %r10
lea addresses_A_ht+0x12e57, %rbp
nop
nop
nop
add $46314, %r10
mov (%rbp), %si
nop
nop
nop
nop
sub $57028, %rdi
pop %rsi
pop %rdi
pop %rcx
pop %rbp
pop %r12
pop %r10
ret
.global s_faulty_load
s_faulty_load:
push %r14
push %r9
push %rbp
push %rbx
push %rcx
push %rdi
push %rdx
push %rsi
// Store
lea addresses_WT+0x173e3, %rbx
nop
nop
nop
sub $40687, %r9
movl $0x51525354, (%rbx)
nop
nop
nop
nop
and %r14, %r14
// REPMOV
lea addresses_UC+0x18af7, %rsi
lea addresses_WC+0x1cff7, %rdi
nop
nop
nop
nop
add $46322, %rdx
mov $9, %rcx
rep movsq
nop
nop
nop
nop
and $42460, %r14
// Store
lea addresses_normal+0x128d3, %rdi
nop
nop
nop
nop
sub %r9, %r9
movl $0x51525354, (%rdi)
nop
nop
cmp $28645, %rbp
// Faulty Load
lea addresses_A+0x13997, %rsi
nop
nop
nop
nop
nop
xor %rdi, %rdi
vmovups (%rsi), %ymm3
vextracti128 $1, %ymm3, %xmm3
vpextrq $0, %xmm3, %rbp
lea oracles, %r14
and $0xff, %rbp
shlq $12, %rbp
mov (%r14,%rbp,1), %rbp
pop %rsi
pop %rdx
pop %rdi
pop %rcx
pop %rbx
pop %rbp
pop %r9
pop %r14
ret
/*
<gen_faulty_load>
[REF]
{'src': {'type': 'addresses_A', 'same': True, 'size': 2, 'congruent': 0, 'NT': False, 'AVXalign': True}, 'OP': 'LOAD'}
{'dst': {'type': 'addresses_WT', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
{'src': {'type': 'addresses_UC', 'congruent': 5, 'same': False}, 'dst': {'type': 'addresses_WC', 'congruent': 5, 'same': False}, 'OP': 'REPM'}
{'dst': {'type': 'addresses_normal', 'same': False, 'size': 4, 'congruent': 2, 'NT': False, 'AVXalign': False}, 'OP': 'STOR'}
[Faulty Load]
{'src': {'type': 'addresses_A', 'same': True, 'size': 32, 'congruent': 0, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
<gen_prepare_buffer>
{'src': {'type': 'addresses_WT_ht', 'congruent': 6, 'same': True}, 'dst': {'type': 'addresses_UC_ht', 'congruent': 8, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_normal_ht', 'congruent': 2, 'same': False}, 'dst': {'type': 'addresses_D_ht', 'congruent': 9, 'same': False}, 'OP': 'REPM'}
{'src': {'type': 'addresses_A_ht', 'same': False, 'size': 2, 'congruent': 5, 'NT': False, 'AVXalign': False}, 'OP': 'LOAD'}
{'00': 1, '35': 21828}
00 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35 35
*/
|
; A037758: Base 4 digits are, in order, the first n terms of the periodic sequence with initial period 3,0,1,2.
; Submitted by Christian Krause
; 3,12,49,198,795,3180,12721,50886,203547,814188,3256753,13027014,52108059,208432236,833728945,3334915782,13339663131,53358652524,213434610097,853738440390,3414953761563,13659815046252,54639260185009
mov $2,3
lpb $0
sub $0,1
add $1,$2
mul $1,4
add $2,21
mod $2,4
lpe
add $1,$2
mov $0,$1
|
[BotW_Gamespeed_V208]
moduleMatches = 0x6267BFD0
.origin = codecave
# Constants
const_0.0:
.float 0.0
const_0.5:
.float 0.5
const_1:
.float 1
const_1.5:
.float 1.5
const_30:
.float 30
busSpeed:
.float 62156250
convSub:
.uint 0x43300000
.uint 0x80000000
# Variables
; Cemu doesn't parse the variables correctly until it saves all the settings. This is just a temporary test of a workaround to make it work.
; To change this workaround back, change the lines from
; ($advancedMode * $fpsLimitAdvanced) + ((($advancedMode+1) % 2) * $fpsLimitNormal)
; to
; $fpsLimit
fpsLimit:
.float (($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal)
lowFPSLimit:
.float $lowFPSLimit
bufferSizeDivider:
.float $frameAverageAmount
averageFPS30:
.float (($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal)
averageFPS30Inv:
.float 900/((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))
averageFPS1.5:
.float (1.5*((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal)))/30
averageFPS1.5Inv:
.float 45/((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))
averageFPS1:
.float ((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))/30
averageFPS1Inv:
.float 30/((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))
averageFPS0.5:
.float ((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))/60
averageFPS0.5Inv:
.float 30/(2*((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal)))
averageSum:
.float ((($advancedMode == 0) * $fpsLimitAdvanced) + (($advancedMode == 1) * $fpsLimitNormal))*$frameAverageAmount
initBuffer:
.byte 0
bufferStart:
.ptr 0xDC
bufferCurrEntry:
.ptr 0xDC
bufferEnd:
.ptr 0xDC+(4*$frameAverageAmount)
; Useful for trying potential FPS values. Need to set debugMode = 1 to enable the debugging in the interface and code.
debugAddr:
.ptr 0x00000000
debugMultiplier:
.float $debugMultiplier
# Code
_calculateGamespeed:
stw r0, 0x78(r30) ; Execute original instruction that got replaced with a jump to this function
; If static FPS is enabled, always set currently "running" FPS to $fpsLimit
li r3, $staticFPSMode ; Load the $staticFPSMode setting into r3
cmpwi r3, 1 ; Compare with 1, which is when it's enabled
bne _checkExternalSpeed ; If the comparison is not equal, run
lis r3, fpsLimit@ha ; Load current FPS limit...
lfs f10, fpsLimit@l(r3) ; ...into f10
b _setGamespeed ; Skip dynamic FPS code when static mode is enabled and go to the game speed setting code
; If the manual speed has been set by an external program to something other then 0, use that as the static speed
_checkExternalSpeed:
lis r11, const_0.0@ha ; Load a 0 float...
lfs f12, const_0.0@l(r11) ; ...into f12
lfs f10, 0xD0(r30) ; Load the external speed offset
fcmpu cr0, f10, f12 ; Compare the value stored in the external memory offset to 0 (f12)
beq _calculateDynamicFPS ; Compare the
b _setGamespeed
; Calculate speed of current frame (FPS). It's calculated by using the ticks between the previous frame and now, which is stored in r12, and the amount of ticks that the Wii U executes in a second (the bus speed).
_calculateDynamicFPS:
xoris r12, r12, 0x8000 ; Flip the sign bit of int ticks for floating point conversion
stw r12, 0xD8(r30) ; Store sign flipped ticks in memory as lower half of double
lis r12, 0x4330 ; Create upper half of ticks double
stw r12, 0xD4(r30) ; Store it in upper half of memory
lfd f10, 0xD4(r30) ; Load full double ticks into f10
lis r12, convSub@ha ; Load number to subtract from tick double...
lfd f12, convSub@l(r12) ; ...to create tick float into f12
fsub f10, f10, f12 ; Do the subtraction
frsp f10, f10 ; Round to single precision and tick float is in f10
lis r12, const_1@ha ; Load float of 1...
lfs f12, const_1@l(r12) ; ...into f12
fdivs f10, f12, f10 ; Divide 1 by ticks
lis r12, busSpeed@ha ; Load wii u bus speed...
lfs f12, busSpeed@l(r12) ; ...into f12
fmuls f10, f12, f10 ; Multiply bus speed to have current fps in f10. (1/ticks)*bus speed
; Initialize the circular buffer with default values whenever a setting gets changed
_initializeAverageBuffer:
lis r12, initBuffer@ha ; Load the initBuffer variable to see whether the buffer has to be initialized/reset again
lbz r11, initBuffer@l(r12) ; ...to check whether/what the current buffer settings are
cmpwi r11, 1 ; Compare the previously $frameAverageAmount with the current $frameAverageAmount
beq _calcAverageFPS ; Continue to calulating the average FPS if the previous settings are the same as the permanently set settings
li r11, 1 ; Load "1" into r11
stb r11, initBuffer@l(r12) ; Store that 1 into the initBuffer so that it will only initialize this once
lis r12, fpsLimit@ha ; Load current FPS limit...
lfs f10, fpsLimit@l(r12) ; ...into f10
lis r12, bufferStart@ha ; Load offset to the start of the averaging buffer...
lwz r12, bufferStart@l(r12) ; ...into r12
lis r3, bufferEnd@ha ; Load offset to the end of the averaging buffer...
lwz r3, bufferEnd@l(r3) ; ...into r3
add r11, r12, r30 ; Make full offset by adding r30 (the empty buffer offset) to r12, which is the buffer offset.
stfs f10, 0x0(r11) ; Store f10 to the address in r12 + 0x04 using this specific instruction, which also adds the 0x04 to r12
addi r12, r12, 0x04 ; Add 0x04 to the buffer offset to make the next entry offset
cmpw r12, r3 ; Compare the current address offset in r12 with the address offset in r3
ble .-0x10 ; Loop back until the whole buffer is initialized with the value from f12
; Calculate the rolling average FPS over the last N amount of frames which are stored in the circular buffer
_calcAverageFPS:
lis r3, bufferCurrEntry@ha ; Load the offset to the current value
lwz r12, bufferCurrEntry@l(r3) ; Load the current buffer offset
lis r11, averageSum@ha ; Load the current average sum
lfs f7, averageSum@l(r11) ; ...into f7
add r3, r12, r30 ; Add r12 to r30 to create the whole offset, since Cemu's assembly doesn't support LFSX and STFX
lfs f12, 0x0(r3) ; Load the value that's stored in the current offset
fadds f7, f7, f10 ; Add the FPS from this current frame
fsubs f7, f7, f12 ; Subtract this value from the current average sum
stfs f7, averageSum@l(r11) ; Store this new average sum again
stfs f10, 0x0(r3) ; Store the FPS value from this current frame in place of the old value
; Store the offset to the next buffer entry
lis r11, bufferEnd@ha ; Load offset to the end of the averaging buffer
lwz r11, bufferEnd@l(r11) ; ...into r11
addi r12, r12, 0x04 ; Add 0x04 to the current entry offset to have the next entry offset
cmpw r11, r12 ; Compare this new entry offset to the end offset
bgt .+0x0C ; Skip the next 2 lines if the next entry offset is smaller
lis r12, bufferStart@ha ; Load start of the buffer offset...
lwz r12, bufferStart@l(r12) ; ...into r12
lis r3, bufferCurrEntry@ha ; Load current buffer entry
stw r12, bufferCurrEntry@l(r3) ; ...into r12
lis r3, bufferSizeDivider@ha ; Load the buffer size divider
lfs f10, bufferSizeDivider@l(r3); ...into f10
fdivs f10, f7, f10 ; Divide the average FPS sum by the buffer size divider to get the average FPS
; Calculates the gamespeed (which is stored in f10 regardless of average or static code path)
_setGamespeed:
; Prevent the FPS from going below 30FPS.
lis r11, lowFPSLimit@ha ; Load the lowest FPS that the game speed may be set to...
lfs f12, lowFPSLimit@l(r11) ; ...into f12
fcmpu cr0, f10, f12 ; Compare the calculated FPS with the lowest FPS limit
bgt .+0x08 ; Skip the next line when the calculated FPS is higher then the low limit
fmr f10, f12 ; ...if this line isn't skipped, set the FPS to that low limit
; Set average speed (30 range)
lis r11, averageFPS30@ha ; Store the calculated FPS...
stfs f10, averageFPS30@l(r11) ; ...to replace constants that normally use 30
; Set average speed (1.5 range)
lis r11, const_1.5@ha ; Load a constant float with 1.5
lfs f7, const_1.5@l(r11) ; ...into f7
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f7, f10, f7 ; Multiply the calculated FPS by 1.5
fdivs f7, f7, f12 ; Divide this new divided calculated FPS by 30
lis r11, averageFPS1.5@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS1.5@l(r11) ; ...to replace constants that normally use 1.5
; Set average speed (1.0 range)
fdivs f7, f10, f12 ; Divide the calculated FPS by 30
lis r11, averageFPS1@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS1@l(r11) ; ...to replace constants that normally use 1
; Set average speed (0.5 range)
fadds f12, f12, f12 ; Add 30.0 to 30.0 to get 60.0
fdivs f7, f10, f12 ; Divide the calculated FPS by 60
lis r11, averageFPS0.5@ha ; Store this new divided calculated FPS...
stfs f7, averageFPS0.5@l(r11) ; ...to replace constants that normally use 0.5
; Set average speed (inverted 30 range)
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f12, f12, f12 ; Multiply 30.0 by 30.0 to get 900.0
fdivs f7, f12, f10 ; Divide 900.0 by the calculated FPS to invert the FPS
lis r11, averageFPS30Inv@ha ; Store the inverted 30.0 float...
stfs f7, averageFPS30Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 1.5 range)
lis r11, const_1.5@ha ; Load a constant float with 1.5...
lfs f7, const_1.5@l(r11) ; ...into f7
lis r11, const_30@ha ; Load a constant float with 30.0...
lfs f12, const_30@l(r11) ; ...into f12
fmuls f7, f7, f12 ; Multiply 30.0 by 1.5 to get 45.0 and store it in f7
fdivs f7, f7, f10 ; Divide 45.0 by the calculated FPS to invert the FPS
lis r11, averageFPS1.5Inv@ha ; Store the inverted 1.5 float...
stfs f7, averageFPS1.5Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 1.0 range)
fdivs f7, f12, f10 ; Divides 30.0 by the calculated FPS to invert the FPS
lis r11, averageFPS1Inv@ha ; Store the inverted 1.0 float...
stfs f7, averageFPS1Inv@l(r11) ; ...to replace constants that are lower when FPS is higher
; Set average speed (inverted 0.5 range)
fadds f7, f10, f10 ; Add the calculated FPS to itself and store it in f7
fdivs f7, f12, f7 ; Divide 30.0 by 2 * the calculated FPS and store it in f7
lis r11, averageFPS0.5Inv@ha ; Store the inverted 0.5 float...
stfs f7, averageFPS0.5Inv@l(r11); ...to replace constants that are lower when FPS is higher
; Check whether debug mode is on
li r11, $debugMode ; Load debugMode value in r11
cmpwi r11, 1 ; Compare the value with 1
bnelr ; If it's not equal, return back to the link register. Otherwise, run the following lines too...
lis r11, debugMultiplier@ha ; Load the debug multiplier...
lfs f12, debugMultiplier@l(r11) ; ...which is used to modify the calulated FPS to experiment with potential FPS values
fmuls f7, f7, f12 ; Multiply the current FPS with this debug multiplier
lis r11, debugAddr@ha ; Load the pointer to the debug value address...
lwz r11, debugAddr@l(r11) ; ...into r11
stfs f7, 0x0(r11) ; Store the multiplied value in the address from the pointer
blr ; Return back to the address stored in the link register
; Multiplies the time draining using the calculated FPS
_changeArrowTimeDrain:
lfs f1, 0xFC(r11) ; Execute original instruction that got replaced with this codecave jump
lis r12, averageFPS1Inv@ha ; Load the average FPS...
lfs f0, averageFPS1Inv@l(r12) ; ...into f0
fmuls f1, f1, f0 ; Multiply the time draining value by the average FPS divider
blr ; Return to the address that's stored in the link register
; Multiplies the distance you travel during the flurry rush dash using the calculated FPS
_changeFlurryRush:
lis r4, averageFPS1@ha ; Load average FPS into f8..
lfs f8, averageFPS1@l(r4) ; ...which is a float register that's safe to use since it's initialized later
fmuls f13, f13, f8 ; Multiply the flurry rush distance (stored in f1) with the FPS multiplier
fcmpu cr0, f13, f29 ; Execute original instruction that got replaced with this codecave jump
blr ; Return to the address that's stored in the link register
# Patches
0x1031E2C0 = .float 2
0x031FACD0 = nop ; Disable vsync
0x031FACF4 = nop ; Disable vsync loop
0x031FA97C = bla _calculateGamespeed ; Replace an instruction that gets called every frame to calculate the FPS
0x100775AC = .float -999.0 ; Disable something that makes thunderblight ganon yeet off
0x02C6B8F8 = bla _changeFlurryRush ; Fix the flurry rush distance
0x02D5F760 = bla _changeArrowTimeDrain ; Fix the stamina drain during arrow time
0x03793328 = nop
0x03793334 = nop
0x03793378 = lis r29, averageFPS1Inv@ha ; Load the calculated FPS value
0x03793380 = lfs f0, averageFPS1Inv@l(r29) ; ...to use that as animation speed
0x0379338C = nop ; Prevent an instruction from overwriting the loaded value
0x03415C1C = lis r12, averageFPS1Inv@ha ; Load the calculated FPS value
0x03415C24 = lfs f0, averageFPS1Inv@l(r12) ; ...to store that for the GUI speed value
0x03415C2C = nop ; Prevent an instruction from overwriting the loaded value
0x02D90D2C = lis r10, averageFPS30@ha
0x02D90D30 = lfs f11, averageFPS30@l(r10)
0x02D90D88 = lis r10, averageFPS30@ha ; Fix stamina regen by loading the calculated FPS value...
0x02D90D8C = lfs f11, averageFPS30@l(r10) ; ...instead of the normal static 30.0 float it uses
0x037DC35C = lis r12, averageFPS1Inv@ha ; Fix audio looping by loading the calculated FPS value...
0x037DC360 = lfs f13, averageFPS1Inv@l(r12) ; ...instead of the normal static 1.0 float it uses
0x02F62B3C = lis r12, averageFPS1Inv@ha ; Fix map scrolling by loading the calculated FPS value...
0x02F62B40 = lfs f0, averageFPS1Inv@l(r12) ; ...instead of the normal static 1.0 float it uses
0x020E730C = lis r12, averageFPS30Inv@ha ; Fix arrow speed by loading the calculated FPS value...
0x020E731C = lfs f13, averageFPS30Inv@l(r12); ...instead of the normal static 30.0 float it uses
0x020E3EB0 = lis r12, averageFPS0.5@ha ; Modify something to do with arrow bounce and distance by loading the calculated FPS value...
0x020E3EB8 = lfs f13, averageFPS0.5@l(r12) ; ...instead of the normal static 0.5 float it uses
0x020E5390 = lis r10, averageFPS0.5@ha ; Modify the distance arrows travel straight by loading the calculated FPS value...
0x020E5398 = lfs f13, averageFPS0.5@l(r10) ; ...instead of the normal static 0.5 float it uses
0x033609D8 = lis r6, averageFPS1Inv@ha ; Fix shield surfing by loading the calculated FPS value...
0x033609E0 = lfs f0, averageFPS1Inv@l(r6) ; ...instead of the normal static 1.0 float it uses
0x02B951E8 = lis r4, averageFPS1.5Inv@ha ; Fix vertical sensitivity while using runes by loading the calculated FPS value...
0x02B951F0 = lfs f11, averageFPS1.5Inv@l(r4); ...instead of the normal static 1.5 float it uses
0x02B95238 = lis r7, averageFPS30@ha ; Fix vertical gyro sensitivity while using runes by loading the calculated FPS value...
0x02B95240 = lfs f9, averageFPS30@l(r7) ; ...instead of the normal static 30.o float it uses
|
/*
This file is part of the PhantomJS project from Ofi Labs.
Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
Copyright (C) 2011 Ivan De Marino <ivan.de.marino@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "phantom.h"
#include <QApplication>
#include <QDir>
#include <QFileInfo>
#include <QFile>
#include <QWebPage>
#include <QDebug>
#include <QMetaObject>
#include <QMetaProperty>
#include "consts.h"
#include "terminal.h"
#include "utils.h"
#include "webpage.h"
#include "webserver.h"
#include "repl.h"
#include "system.h"
#include "callback.h"
#include "cookiejar.h"
#include "childprocess.h"
static Phantom *phantomInstance = NULL;
// private:
Phantom::Phantom(QObject *parent)
: QObject(parent)
, m_terminated(false)
, m_returnValue(0)
, m_filesystem(0)
, m_system(0)
, m_childprocess(0)
{
QStringList args = QApplication::arguments();
// Prepare the configuration object based on the command line arguments.
// Because this object will be used by other classes, it needs to be ready ASAP.
m_config.init(&args);
// Apply debug configuration as early as possible
Utils::printDebugMessages = m_config.printDebugMessages();
}
void Phantom::init()
{
if (m_config.helpFlag()) {
Terminal::instance()->cout(QString("%1").arg(m_config.helpText()));
Terminal::instance()->cout("Any of the options that accept boolean values ('true'/'false') can also accept 'yes'/'no'.");
Terminal::instance()->cout("");
Terminal::instance()->cout("Without any argument, PhantomJS will launch in interactive mode (REPL).");
Terminal::instance()->cout("");
Terminal::instance()->cout("Documentation can be found at the web site, http://phantomjs.org.");
Terminal::instance()->cout("");
m_terminated = true;
return;
}
if (m_config.versionFlag()) {
m_terminated = true;
Terminal::instance()->cout(QString("%1").arg(PHANTOMJS_VERSION_STRING));
return;
}
if (!m_config.unknownOption().isEmpty()) {
Terminal::instance()->cerr(m_config.unknownOption());
m_terminated = true;
return;
}
// Initialize the CookieJar
CookieJar::instance(m_config.cookiesFile());
m_page = new WebPage(this, QUrl::fromLocalFile(m_config.scriptFile()));
m_pages.append(m_page);
// Set up proxy if required
QString proxyType = m_config.proxyType();
if (proxyType != "none") {
setProxy(m_config.proxyHost(), m_config.proxyPort(), proxyType, m_config.proxyAuthUser(), m_config.proxyAuthPass());
}
// Set output encoding
Terminal::instance()->setEncoding(m_config.outputEncoding());
// Set script file encoding
m_scriptFileEnc.setEncoding(m_config.scriptEncoding());
connect(m_page, SIGNAL(javaScriptConsoleMessageSent(QString)),
SLOT(printConsoleMessage(QString)));
connect(m_page, SIGNAL(initialized()),
SLOT(onInitialized()));
m_defaultPageSettings[PAGE_SETTINGS_LOAD_IMAGES] = QVariant::fromValue(m_config.autoLoadImages());
m_defaultPageSettings[PAGE_SETTINGS_PLUGINS_ENABLED] = QVariant::fromValue(true);
m_defaultPageSettings[PAGE_SETTINGS_JS_ENABLED] = QVariant::fromValue(true);
m_defaultPageSettings[PAGE_SETTINGS_XSS_AUDITING] = QVariant::fromValue(false);
m_defaultPageSettings[PAGE_SETTINGS_USER_AGENT] = QVariant::fromValue(m_page->userAgent());
m_defaultPageSettings[PAGE_SETTINGS_LOCAL_ACCESS_REMOTE] = QVariant::fromValue(m_config.localToRemoteUrlAccessEnabled());
m_defaultPageSettings[PAGE_SETTINGS_WEB_SECURITY_ENABLED] = QVariant::fromValue(m_config.webSecurityEnabled());
m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_OPEN_WINDOWS] = QVariant::fromValue(m_config.javascriptCanOpenWindows());
m_defaultPageSettings[PAGE_SETTINGS_JS_CAN_CLOSE_WINDOWS] = QVariant::fromValue(m_config.javascriptCanCloseWindows());
m_page->applySettings(m_defaultPageSettings);
setLibraryPath(QFileInfo(m_config.scriptFile()).dir().absolutePath());
}
// public:
Phantom *Phantom::instance() {
if (NULL == phantomInstance) {
phantomInstance = new Phantom();
phantomInstance->init();
}
return phantomInstance;
}
Phantom::~Phantom()
{
// Nothing to do: cleanup is handled by QObject relationships
}
QStringList Phantom::args() const
{
return m_config.scriptArgs();
}
QVariantMap Phantom::defaultPageSettings() const
{
return m_defaultPageSettings;
}
QString Phantom::outputEncoding() const
{
return Terminal::instance()->getEncoding();
}
void Phantom::setOutputEncoding(const QString &encoding)
{
Terminal::instance()->setEncoding(encoding);
}
bool Phantom::execute()
{
if (m_terminated)
return false;
#ifndef QT_NO_DEBUG_OUTPUT
qDebug() << "Phantom - execute: Configuration";
const QMetaObject* configMetaObj = m_config.metaObject();
for (int i = 0, ilen = configMetaObj->propertyCount(); i < ilen; ++i) {
qDebug() << " " << i << configMetaObj->property(i).name() << ":" << m_config.property(configMetaObj->property(i).name()).toString();
}
qDebug() << "Phantom - execute: Script & Arguments";
qDebug() << " " << "script:" << m_config.scriptFile();
QStringList args = m_config.scriptArgs();
for (int i = 0, ilen = args.length(); i < ilen; ++i) {
qDebug() << " " << i << "arg:" << args.at(i);
}
#endif
if (m_config.isWebdriverMode()) { // Remote WebDriver mode requested
qDebug() << "Phantom - execute: Starting Remote WebDriver mode";
Terminal::instance()->cout("PhantomJS is launching GhostDriver...");
if (!Utils::injectJsInFrame(":/ghostdriver/main.js", m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), true)) {
m_returnValue = -1;
return false;
}
} else if (m_config.scriptFile().isEmpty()) { // REPL mode requested
qDebug() << "Phantom - execute: Starting REPL mode";
// Create the REPL: it will launch itself, no need to store this variable.
REPL::getInstance(m_page->mainFrame(), this);
} else { // Load the User Script
qDebug() << "Phantom - execute: Starting normal mode";
if (m_config.debug()) {
// Debug enabled
if (!Utils::loadJSForDebug(m_config.scriptFile(), m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), m_config.remoteDebugAutorun())) {
m_returnValue = -1;
return false;
}
m_page->showInspector(m_config.remoteDebugPort());
} else {
if (!Utils::injectJsInFrame(m_config.scriptFile(), m_scriptFileEnc, QDir::currentPath(), m_page->mainFrame(), true)) {
m_returnValue = -1;
return false;
}
}
}
return !m_terminated;
}
int Phantom::returnValue() const
{
return m_returnValue;
}
QString Phantom::libraryPath() const
{
return m_page->libraryPath();
}
void Phantom::setLibraryPath(const QString &libraryPath)
{
m_page->setLibraryPath(libraryPath);
}
QString Phantom::scriptName() const
{
return QFileInfo(m_config.scriptFile()).fileName();
}
QVariantMap Phantom::version() const
{
QVariantMap result;
result["major"] = PHANTOMJS_VERSION_MAJOR;
result["minor"] = PHANTOMJS_VERSION_MINOR;
result["patch"] = PHANTOMJS_VERSION_PATCH;
return result;
}
QObject *Phantom::page() const
{
return m_page;
}
Config *Phantom::config()
{
return &m_config;
}
bool Phantom::printDebugMessages() const
{
return m_config.printDebugMessages();
}
bool Phantom::areCookiesEnabled() const
{
return CookieJar::instance()->isEnabled();
}
void Phantom::setCookiesEnabled(const bool value)
{
if (value) {
CookieJar::instance()->enable();
} else {
CookieJar::instance()->disable();
}
}
bool Phantom::webdriverMode() const
{
return m_config.isWebdriverMode();
}
// public slots:
QObject *Phantom::createWebPage()
{
WebPage *page = new WebPage(this);
// Store pointer to the page for later cleanup
m_pages.append(page);
// Apply default settings to the page
page->applySettings(m_defaultPageSettings);
// Show web-inspector if in debug mode
if (m_config.debug()) {
page->showInspector(m_config.remoteDebugPort());
}
return page;
}
QObject* Phantom::createWebServer()
{
WebServer *server = new WebServer(this);
m_servers.append(server);
return server;
}
QObject *Phantom::createFilesystem()
{
if (!m_filesystem)
m_filesystem = new FileSystem(this);
return m_filesystem;
}
QObject *Phantom::createSystem()
{
if (!m_system) {
m_system = new System(this);
QStringList systemArgs;
systemArgs += m_config.scriptFile();
systemArgs += m_config.scriptArgs();
m_system->setArgs(systemArgs);
}
return m_system;
}
QObject *Phantom::_createChildProcess()
{
if (!m_childprocess) {
m_childprocess = new ChildProcess(this);
}
return m_childprocess;
}
QObject* Phantom::createCallback()
{
return new Callback(this);
}
void Phantom::loadModule(const QString &moduleSource, const QString &filename)
{
if (m_terminated)
return;
QString scriptSource =
"(function(require, exports, module) {" +
moduleSource +
"}.call({}," +
"require.cache['" + filename + "']._getRequire()," +
"require.cache['" + filename + "'].exports," +
"require.cache['" + filename + "']" +
"));";
m_page->mainFrame()->evaluateJavaScript(scriptSource, filename);
}
bool Phantom::injectJs(const QString &jsFilePath)
{
QString pre = "";
qDebug() << "Phantom - injectJs:" << jsFilePath;
// If in Remote Webdriver Mode, we need to manipulate the PATH, to point it to a resource in `ghostdriver.qrc`
if (webdriverMode()) {
pre = ":/ghostdriver/";
qDebug() << "Phantom - injectJs: prepending" << pre;
}
if (m_terminated)
return false;
return Utils::injectJsInFrame(pre + jsFilePath, libraryPath(), m_page->mainFrame());
}
void Phantom::setProxy(const QString &ip, const qint64 &port, const QString &proxyType, const QString &user, const QString &password)
{
qDebug() << "Set " << proxyType << " proxy to: " << ip << ":" << port;
if (ip.isEmpty()) {
QNetworkProxyFactory::setUseSystemConfiguration(true);
} else {
QNetworkProxy::ProxyType networkProxyType = QNetworkProxy::HttpProxy;
if (proxyType == "socks5") {
networkProxyType = QNetworkProxy::Socks5Proxy;
}
// Checking for passed proxy user and password
if(!user.isEmpty() && !password.isEmpty()) {
QNetworkProxy proxy(networkProxyType, ip, port, user, password);
QNetworkProxy::setApplicationProxy(proxy);
} else {
QNetworkProxy proxy(networkProxyType, ip, port);
QNetworkProxy::setApplicationProxy(proxy);
}
}
}
void Phantom::exit(int code)
{
if (m_config.debug()) {
Terminal::instance()->cout("Phantom::exit() called but not quitting in debug mode.");
} else {
doExit(code);
}
}
void Phantom::debugExit(int code)
{
doExit(code);
}
// private slots:
void Phantom::printConsoleMessage(const QString &message)
{
Terminal::instance()->cout(message);
}
void Phantom::onInitialized()
{
// Add 'phantom' object to the global scope
m_page->mainFrame()->addToJavaScriptWindowObject("phantom", this);
// Bootstrap the PhantomJS scope
m_page->mainFrame()->evaluateJavaScript(
Utils::readResourceFileUtf8(":/bootstrap.js"),
QString("phantomjs://bootstrap.js")
);
}
bool Phantom::setCookies(const QVariantList &cookies)
{
// Delete all the cookies from the CookieJar
CookieJar::instance()->clearCookies();
// Add a new set of cookies
return CookieJar::instance()->addCookiesFromMap(cookies);
}
QVariantList Phantom::cookies() const
{
// Return all the Cookies in the CookieJar, as a list of Maps (aka JSON in JS space)
return CookieJar::instance()->cookiesToMap();
}
bool Phantom::addCookie(const QVariantMap &cookie)
{
return CookieJar::instance()->addCookieFromMap(cookie);
}
bool Phantom::deleteCookie(const QString &cookieName)
{
if (!cookieName.isEmpty()) {
return CookieJar::instance()->deleteCookie(cookieName);
}
return false;
}
void Phantom::clearCookies()
{
CookieJar::instance()->clearCookies();
}
// private:
void Phantom::doExit(int code)
{
if (m_config.debug())
{
Utils::cleanupFromDebug();
}
emit aboutToExit(code);
m_terminated = true;
m_returnValue = code;
qDeleteAll(m_pages);
m_pages.clear();
m_page = 0;
QApplication::instance()->exit(code);
}
|
; A288712: Positions of 0 in A288711; complement of A288713.
; 2,3,4,5,6,8,9,10,11,12,14,15,16,18,19,20,21,22,24,25,26,27,28,30,31,32,34,35,36,37,38,40,41,42,44,45,46,47,48,50,51,52,53,54,56,57,58,60,61,62,63,64,66,67,68,69,70,72,73,74,76,77,78,79,80,82,83,84,86,87,88,89,90,92,93,94,95,96,98,99,100,102,103,104,105,106,108,109,110,112,113,114,115,116,118,119,120,121,122,124,125,126,128,129,130,131,132,134,135,136,137,138,140,141,142,144,145,146,147,148,150,151,152,154,155,156,157,158,160,161,162,163,164,166,167,168,170,171,172,173,174,176,177,178,179,180,182,183,184,186,187,188,189,190,192,193,194,196,197,198,199,200,202,203,204,205,206,208,209,210,212,213,214,215,216,218,219,220,222,223,224,225,226,228,229,230,231,232,234,235,236,238,239,240,241,242,244,245,246,247,248,250,251,252,254,255,256,257,258,260,261,262,264,265,266,267,268,270,271,272,273,274,276,277,278,280,281,282,283,284,286,287,288,290,291,292,293,294,296,297,298,299,300,302,303,304,306,307,308,309
mov $2,$0
mov $3,2
mov $4,$0
lpb $3,1
mov $0,$2
sub $0,1
trn $0,1
sub $3,1
cal $0,192002 ; Counting sequence for Wythoff AB-numbers smaller than n.
add $0,1
lpe
mov $1,$0
add $1,1
add $1,$4
|
; A049867: a(n)=Sum{a(k): k=0,1,2,...,n-4,n-2,n-1}; a(n-3) is not a summand; 3 initial terms required.
; Submitted by Stefano Spezia
; 1,1,4,5,10,17,33,61,115,214,400,746,1393,2600,4854,9061,16915,31576,58945,110036,205411,383453,715815,1336255,2494468,4656574,8692708,16227203,30292300,56548466,105562437,197059777,367863388
mov $1,2
mov $2,2
mov $4,-1
mov $5,1
lpb $0
sub $0,1
sub $3,$4
add $1,$3
mov $3,$4
mov $4,$2
mov $2,$3
add $2,$1
sub $5,1
add $5,$4
mov $3,$5
lpe
mov $0,$2
sub $0,1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.